Skip to content

Commit fb91e5e

Browse files
committed
rustc_target: Stop using "string typing" for relocation models
Introduce `enum RelocModel` instead.
1 parent 019ab73 commit fb91e5e

30 files changed

+150
-108
lines changed

src/librustc_codegen_llvm/back/write.rs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::back::profiling::{
77
use crate::base;
88
use crate::common;
99
use crate::consts;
10-
use crate::context::{get_reloc_model, is_pie_binary};
10+
use crate::context::is_pie_binary;
1111
use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
1212
use crate::llvm_util;
1313
use crate::type_::Type;
@@ -25,6 +25,7 @@ use rustc_middle::bug;
2525
use rustc_middle::ty::TyCtxt;
2626
use rustc_session::config::{self, Lto, OutputType, Passes, Sanitizer, SwitchWithOptPath};
2727
use rustc_session::Session;
28+
use rustc_target::spec::RelocModel;
2829

2930
use libc::{c_char, c_int, c_uint, c_void, size_t};
3031
use std::ffi::CString;
@@ -35,16 +36,6 @@ use std::slice;
3536
use std::str;
3637
use std::sync::Arc;
3738

38-
pub const RELOC_MODEL_ARGS: [(&str, llvm::RelocMode); 7] = [
39-
("pic", llvm::RelocMode::PIC),
40-
("static", llvm::RelocMode::Static),
41-
("default", llvm::RelocMode::Default),
42-
("dynamic-no-pic", llvm::RelocMode::DynamicNoPic),
43-
("ropi", llvm::RelocMode::ROPI),
44-
("rwpi", llvm::RelocMode::RWPI),
45-
("ropi-rwpi", llvm::RelocMode::ROPI_RWPI),
46-
];
47-
4839
pub const CODE_GEN_MODEL_ARGS: &[(&str, llvm::CodeModel)] = &[
4940
("small", llvm::CodeModel::Small),
5041
("kernel", llvm::CodeModel::Kernel),
@@ -126,6 +117,17 @@ fn to_pass_builder_opt_level(cfg: config::OptLevel) -> llvm::PassBuilderOptLevel
126117
}
127118
}
128119

120+
fn to_llvm_relocation_model(relocation_model: RelocModel) -> llvm::RelocMode {
121+
match relocation_model {
122+
RelocModel::Static => llvm::RelocMode::Static,
123+
RelocModel::Pic => llvm::RelocMode::PIC,
124+
RelocModel::DynamicNoPic => llvm::RelocMode::DynamicNoPic,
125+
RelocModel::Ropi => llvm::RelocMode::ROPI,
126+
RelocModel::Rwpi => llvm::RelocMode::RWPI,
127+
RelocModel::RopiRwpi => llvm::RelocMode::ROPI_RWPI,
128+
}
129+
}
130+
129131
// If find_features is true this won't access `sess.crate_types` by assuming
130132
// that `is_pie_binary` is false. When we discover LLVM target features
131133
// `sess.crate_types` is uninitialized so we cannot access it.
@@ -134,7 +136,7 @@ pub fn target_machine_factory(
134136
optlvl: config::OptLevel,
135137
find_features: bool,
136138
) -> Arc<dyn Fn() -> Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
137-
let reloc_model = get_reloc_model(sess);
139+
let reloc_model = to_llvm_relocation_model(sess.relocation_model());
138140

139141
let (opt_level, _) = to_llvm_opt_settings(optlvl);
140142
let use_softfp = sess.opts.cg.soft_float;

src/librustc_codegen_llvm/context.rs

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use rustc_session::Session;
2121
use rustc_span::source_map::{Span, DUMMY_SP};
2222
use rustc_span::symbol::Symbol;
2323
use rustc_target::abi::{HasDataLayout, LayoutOf, PointeeInfo, Size, TargetDataLayout, VariantIdx};
24-
use rustc_target::spec::{HasTargetSpec, Target};
24+
use rustc_target::spec::{HasTargetSpec, RelocModel, Target};
2525

2626
use std::cell::{Cell, RefCell};
2727
use std::ffi::CStr;
@@ -87,22 +87,6 @@ pub struct CodegenCx<'ll, 'tcx> {
8787
local_gen_sym_counter: Cell<usize>,
8888
}
8989

90-
pub fn get_reloc_model(sess: &Session) -> llvm::RelocMode {
91-
let reloc_model_arg = match sess.opts.cg.relocation_model {
92-
Some(ref s) => &s[..],
93-
None => &sess.target.target.options.relocation_model[..],
94-
};
95-
96-
match crate::back::write::RELOC_MODEL_ARGS.iter().find(|&&arg| arg.0 == reloc_model_arg) {
97-
Some(x) => x.1,
98-
_ => {
99-
sess.err(&format!("{:?} is not a valid relocation mode", reloc_model_arg));
100-
sess.abort_if_errors();
101-
bug!();
102-
}
103-
}
104-
}
105-
10690
fn get_tls_model(sess: &Session) -> llvm::ThreadLocalMode {
10791
let tls_model_arg = match sess.opts.debugging_opts.tls_model {
10892
Some(ref s) => &s[..],
@@ -119,12 +103,9 @@ fn get_tls_model(sess: &Session) -> llvm::ThreadLocalMode {
119103
}
120104
}
121105

122-
fn is_any_library(sess: &Session) -> bool {
123-
sess.crate_types.borrow().iter().any(|ty| *ty != config::CrateType::Executable)
124-
}
125-
126106
pub fn is_pie_binary(sess: &Session) -> bool {
127-
!is_any_library(sess) && get_reloc_model(sess) == llvm::RelocMode::PIC
107+
sess.relocation_model() == RelocModel::Pic
108+
&& !sess.crate_types.borrow().iter().any(|ty| *ty != config::CrateType::Executable)
128109
}
129110

130111
fn strip_function_ptr_alignment(data_layout: String) -> String {
@@ -200,7 +181,7 @@ pub unsafe fn create_module(
200181
let llvm_target = SmallCStr::new(&sess.target.target.llvm_target);
201182
llvm::LLVMRustSetNormalizedTarget(llmod, llvm_target.as_ptr());
202183

203-
if get_reloc_model(sess) == llvm::RelocMode::PIC {
184+
if sess.relocation_model() == RelocModel::Pic {
204185
llvm::LLVMRustSetModulePICLevel(llmod);
205186
}
206187

src/librustc_codegen_llvm/lib.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,9 @@ impl CodegenBackend for LlvmCodegenBackend {
201201
match req {
202202
PrintRequest::RelocationModels => {
203203
println!("Available relocation models:");
204-
for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
204+
for name in
205+
&["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
206+
{
205207
println!(" {}", name);
206208
}
207209
println!();

src/librustc_codegen_llvm/llvm/ffi.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,6 @@ pub struct SanitizerOptions {
446446
#[derive(Copy, Clone, PartialEq)]
447447
#[repr(C)]
448448
pub enum RelocMode {
449-
Default,
450449
Static,
451450
PIC,
452451
DynamicNoPic,

src/librustc_codegen_ssa/back/link.rs

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use rustc_session::search_paths::PathKind;
1212
/// need out of the shared crate context before we get rid of it.
1313
use rustc_session::{filesearch, Session};
1414
use rustc_span::symbol::Symbol;
15-
use rustc_target::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelroLevel};
15+
use rustc_target::spec::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, RelroLevel};
1616

1717
use super::archive::ArchiveBuilder;
1818
use super::command::Command;
@@ -1352,7 +1352,7 @@ fn add_position_independent_executable_args(
13521352
if sess.target.target.options.position_independent_executables {
13531353
let attr_link_args = &*codegen_results.crate_info.link_args;
13541354
let mut user_defined_link_args = sess.opts.cg.link_args.iter().chain(attr_link_args);
1355-
if is_pic(sess)
1355+
if sess.relocation_model() == RelocModel::Pic
13561356
&& !sess.crt_static(Some(crate_type))
13571357
&& !user_defined_link_args.any(|x| x == "-static")
13581358
{
@@ -1992,12 +1992,3 @@ fn are_upstream_rust_objects_already_included(sess: &Session) -> bool {
19921992
config::Lto::No | config::Lto::ThinLocal => false,
19931993
}
19941994
}
1995-
1996-
fn is_pic(sess: &Session) -> bool {
1997-
let reloc_model_arg = match sess.opts.cg.relocation_model {
1998-
Some(ref s) => &s[..],
1999-
None => &sess.target.target.options.relocation_model[..],
2000-
};
2001-
2002-
reloc_model_arg == "pic"
2003-
}

src/librustc_interface/tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use rustc_session::{build_session, Session};
1414
use rustc_span::edition::{Edition, DEFAULT_EDITION};
1515
use rustc_span::symbol::sym;
1616
use rustc_span::SourceFileHashAlgorithm;
17-
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
17+
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelocModel, RelroLevel};
1818
use std::collections::{BTreeMap, BTreeSet};
1919
use std::iter::FromIterator;
2020
use std::path::PathBuf;
@@ -430,7 +430,7 @@ fn test_codegen_options_tracking_hash() {
430430
tracked!(prefer_dynamic, true);
431431
tracked!(profile_generate, SwitchWithOptPath::Enabled(None));
432432
tracked!(profile_use, Some(PathBuf::from("abc")));
433-
tracked!(relocation_model, Some(String::from("relocation model")));
433+
tracked!(relocation_model, Some(RelocModel::Pic));
434434
tracked!(soft_float, true);
435435
tracked!(target_cpu, Some(String::from("abc")));
436436
tracked!(target_feature, String::from("all the features, all of them"));

src/librustc_session/config.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1311,10 +1311,6 @@ fn collect_print_requests(
13111311
prints.push(PrintRequest::TargetFeatures);
13121312
cg.target_feature = String::new();
13131313
}
1314-
if cg.relocation_model.as_ref().map_or(false, |s| s == "help") {
1315-
prints.push(PrintRequest::RelocationModels);
1316-
cg.relocation_model = None;
1317-
}
13181314
if cg.code_model.as_ref().map_or(false, |s| s == "help") {
13191315
prints.push(PrintRequest::CodeModels);
13201316
cg.code_model = None;
@@ -2005,7 +2001,7 @@ crate mod dep_tracking {
20052001
use crate::utils::NativeLibraryKind;
20062002
use rustc_feature::UnstableFeatures;
20072003
use rustc_span::edition::Edition;
2008-
use rustc_target::spec::{MergeFunctions, PanicStrategy, RelroLevel, TargetTriple};
2004+
use rustc_target::spec::{MergeFunctions, PanicStrategy, RelocModel, RelroLevel, TargetTriple};
20092005
use std::collections::hash_map::DefaultHasher;
20102006
use std::collections::BTreeMap;
20112007
use std::hash::Hash;
@@ -2053,6 +2049,7 @@ crate mod dep_tracking {
20532049
impl_dep_tracking_hash_via_hash!(Option<(String, u64)>);
20542050
impl_dep_tracking_hash_via_hash!(Option<Vec<String>>);
20552051
impl_dep_tracking_hash_via_hash!(Option<MergeFunctions>);
2052+
impl_dep_tracking_hash_via_hash!(Option<RelocModel>);
20562053
impl_dep_tracking_hash_via_hash!(Option<PanicStrategy>);
20572054
impl_dep_tracking_hash_via_hash!(Option<RelroLevel>);
20582055
impl_dep_tracking_hash_via_hash!(Option<lint::Level>);

src/librustc_session/options.rs

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::search_paths::SearchPath;
66
use crate::utils::NativeLibraryKind;
77

88
use rustc_target::spec::TargetTriple;
9-
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
9+
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelocModel, RelroLevel};
1010

1111
use rustc_feature::UnstableFeatures;
1212
use rustc_span::edition::Edition;
@@ -265,14 +265,13 @@ macro_rules! options {
265265
pub const parse_merge_functions: &str = "one of: `disabled`, `trampolines`, or `aliases`";
266266
pub const parse_symbol_mangling_version: &str = "either `legacy` or `v0` (RFC 2603)";
267267
pub const parse_src_file_hash: &str = "either `md5` or `sha1`";
268+
pub const parse_relocation_model: &str =
269+
"one of supported relocation models (`rustc --print relocation-models`)";
268270
}
269271

270272
#[allow(dead_code)]
271273
mod $mod_set {
272-
use super::{$struct_name, Passes, Sanitizer, LtoCli, LinkerPluginLto, SwitchWithOptPath,
273-
SymbolManglingVersion, CFGuard, SourceFileHashAlgorithm};
274-
use rustc_target::spec::{LinkerFlavor, MergeFunctions, PanicStrategy, RelroLevel};
275-
use std::path::PathBuf;
274+
use super::*;
276275
use std::str::FromStr;
277276

278277
// Sometimes different options need to build a common structure.
@@ -598,6 +597,15 @@ macro_rules! options {
598597
true
599598
}
600599

600+
fn parse_relocation_model(slot: &mut Option<RelocModel>, v: Option<&str>) -> bool {
601+
match v.and_then(|s| RelocModel::from_str(s).ok()) {
602+
Some(relocation_model) => *slot = Some(relocation_model),
603+
None if v == Some("default") => *slot = None,
604+
_ => return false,
605+
}
606+
true
607+
}
608+
601609
fn parse_symbol_mangling_version(
602610
slot: &mut SymbolManglingVersion,
603611
v: Option<&str>,
@@ -697,7 +705,7 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
697705
"compile the program with profiling instrumentation"),
698706
profile_use: Option<PathBuf> = (None, parse_opt_pathbuf, [TRACKED],
699707
"use the given `.profdata` file for profile-guided optimization"),
700-
relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
708+
relocation_model: Option<RelocModel> = (None, parse_relocation_model, [TRACKED],
701709
"choose the relocation model to use (`rustc --print relocation-models` for details)"),
702710
remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
703711
"print remarks for these optimization passes (space separated, or \"all\")"),

src/librustc_session/session.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticId, ErrorReported
2222
use rustc_span::edition::Edition;
2323
use rustc_span::source_map::{self, FileLoader, MultiSpan, RealFileLoader, SourceMap, Span};
2424
use rustc_span::SourceFileHashAlgorithm;
25-
use rustc_target::spec::{PanicStrategy, RelroLevel, Target, TargetTriple};
25+
use rustc_target::spec::{PanicStrategy, RelocModel, RelroLevel, Target, TargetTriple};
2626

2727
use std::cell::{self, RefCell};
2828
use std::env;
@@ -584,6 +584,10 @@ impl Session {
584584
}
585585
}
586586

587+
pub fn relocation_model(&self) -> RelocModel {
588+
self.opts.cg.relocation_model.unwrap_or(self.target.target.options.relocation_model)
589+
}
590+
587591
pub fn must_not_eliminate_frame_pointers(&self) -> bool {
588592
// "mcount" function relies on stack pointer.
589593
// See <https://sourceware.org/binutils/docs/gprof/Implementation.html>.

src/librustc_target/spec/aarch64_unknown_none.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,14 @@
66
//
77
// For example, `-C target-cpu=cortex-a53`.
88

9-
use super::{LinkerFlavor, LldFlavor, PanicStrategy, Target, TargetOptions};
9+
use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, Target, TargetOptions};
1010

1111
pub fn target() -> Result<Target, String> {
1212
let opts = TargetOptions {
1313
linker: Some("rust-lld".to_owned()),
1414
features: "+strict-align,+neon,+fp-armv8".to_string(),
1515
executables: true,
16-
relocation_model: "static".to_string(),
16+
relocation_model: RelocModel::Static,
1717
disable_redzone: true,
1818
linker_is_gnu: true,
1919
max_atomic_width: Some(128),

0 commit comments

Comments
 (0)