Skip to content

Commit 3bd8ac8

Browse files
authored
Rollup merge of rust-lang#104001 - Ayush1325:custom-entry, r=bjorn3
Improve generating Custom entry function This commit is aimed at making compiler-generated entry functions (Basically just C `main` right now) more generic so other targets can do similar things for custom entry. This was initially implemented as part of rust-lang#100316. Currently, this moves the entry function name and Call convention to the target spec. Signed-off-by: Ayush Singh <[email protected]>
2 parents 4ca5ece + 2436dff commit 3bd8ac8

File tree

11 files changed

+161
-36
lines changed

11 files changed

+161
-36
lines changed

Diff for: compiler/rustc_codegen_cranelift/src/abi/mod.rs

+15-10
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,19 @@ fn clif_sig_from_fn_abi<'tcx>(
2222
default_call_conv: CallConv,
2323
fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
2424
) -> Signature {
25-
let call_conv = match fn_abi.conv {
25+
let call_conv = conv_to_call_conv(fn_abi.conv, default_call_conv);
26+
27+
let inputs = fn_abi.args.iter().map(|arg_abi| arg_abi.get_abi_param(tcx).into_iter()).flatten();
28+
29+
let (return_ptr, returns) = fn_abi.ret.get_abi_return(tcx);
30+
// Sometimes the first param is an pointer to the place where the return value needs to be stored.
31+
let params: Vec<_> = return_ptr.into_iter().chain(inputs).collect();
32+
33+
Signature { params, returns, call_conv }
34+
}
35+
36+
pub(crate) fn conv_to_call_conv(c: Conv, default_call_conv: CallConv) -> CallConv {
37+
match c {
2638
Conv::Rust | Conv::C => default_call_conv,
2739
Conv::RustCold => CallConv::Cold,
2840
Conv::X86_64SysV => CallConv::SystemV,
@@ -38,15 +50,8 @@ fn clif_sig_from_fn_abi<'tcx>(
3850
| Conv::X86VectorCall
3951
| Conv::AmdGpuKernel
4052
| Conv::AvrInterrupt
41-
| Conv::AvrNonBlockingInterrupt => todo!("{:?}", fn_abi.conv),
42-
};
43-
let inputs = fn_abi.args.iter().map(|arg_abi| arg_abi.get_abi_param(tcx).into_iter()).flatten();
44-
45-
let (return_ptr, returns) = fn_abi.ret.get_abi_return(tcx);
46-
// Sometimes the first param is an pointer to the place where the return value needs to be stored.
47-
let params: Vec<_> = return_ptr.into_iter().chain(inputs).collect();
48-
49-
Signature { params, returns, call_conv }
53+
| Conv::AvrNonBlockingInterrupt => todo!("{:?}", c),
54+
}
5055
}
5156

5257
pub(crate) fn get_function_sig<'tcx>(

Diff for: compiler/rustc_codegen_cranelift/src/main_shim.rs

+6-2
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,14 @@ pub(crate) fn maybe_create_entry_wrapper(
6363
AbiParam::new(m.target_config().pointer_type()),
6464
],
6565
returns: vec![AbiParam::new(m.target_config().pointer_type() /*isize*/)],
66-
call_conv: CallConv::triple_default(m.isa().triple()),
66+
call_conv: crate::conv_to_call_conv(
67+
tcx.sess.target.options.entry_abi,
68+
CallConv::triple_default(m.isa().triple()),
69+
),
6770
};
6871

69-
let cmain_func_id = m.declare_function("main", Linkage::Export, &cmain_sig).unwrap();
72+
let entry_name = tcx.sess.target.options.entry_name.as_ref();
73+
let cmain_func_id = m.declare_function(entry_name, Linkage::Export, &cmain_sig).unwrap();
7074

7175
let instance = Instance::mono(tcx, rust_main_def_id).polymorphize(tcx);
7276

Diff for: compiler/rustc_codegen_gcc/src/context.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -425,8 +425,9 @@ impl<'gcc, 'tcx> MiscMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
425425
}
426426

427427
fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
428-
if self.get_declared_value("main").is_none() {
429-
Some(self.declare_cfn("main", fn_type))
428+
let entry_name = self.sess().target.entry_name.as_ref();
429+
if self.get_declared_value(entry_name).is_none() {
430+
Some(self.declare_entry_fn(entry_name, fn_type, ()))
430431
}
431432
else {
432433
// If the symbol already exists, it is an error: for example, the user wrote

Diff for: compiler/rustc_codegen_gcc/src/declare.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,13 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
6565
global
6666
}
6767

68-
pub fn declare_cfn(&self, name: &str, _fn_type: Type<'gcc>) -> RValue<'gcc> {
68+
pub fn declare_entry_fn(&self, name: &str, _fn_type: Type<'gcc>, callconv: () /*llvm::CCallConv*/) -> RValue<'gcc> {
6969
// TODO(antoyo): use the fn_type parameter.
7070
let const_string = self.context.new_type::<u8>().make_pointer().make_pointer();
7171
let return_type = self.type_i32();
7272
let variadic = false;
7373
self.linkage.set(FunctionType::Exported);
74-
let func = declare_raw_fn(self, name, () /*llvm::CCallConv*/, return_type, &[self.type_i32(), const_string], variadic);
74+
let func = declare_raw_fn(self, name, callconv, return_type, &[self.type_i32(), const_string], variadic);
7575
// NOTE: it is needed to set the current_func here as well, because get_fn() is not called
7676
// for the main function.
7777
*self.current_func.borrow_mut() = Some(func);

Diff for: compiler/rustc_codegen_llvm/src/abi.rs

+23-17
Original file line numberDiff line numberDiff line change
@@ -398,23 +398,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> {
398398
}
399399

400400
fn llvm_cconv(&self) -> llvm::CallConv {
401-
match self.conv {
402-
Conv::C | Conv::Rust | Conv::CCmseNonSecureCall => llvm::CCallConv,
403-
Conv::RustCold => llvm::ColdCallConv,
404-
Conv::AmdGpuKernel => llvm::AmdGpuKernel,
405-
Conv::AvrInterrupt => llvm::AvrInterrupt,
406-
Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
407-
Conv::ArmAapcs => llvm::ArmAapcsCallConv,
408-
Conv::Msp430Intr => llvm::Msp430Intr,
409-
Conv::PtxKernel => llvm::PtxKernel,
410-
Conv::X86Fastcall => llvm::X86FastcallCallConv,
411-
Conv::X86Intr => llvm::X86_Intr,
412-
Conv::X86Stdcall => llvm::X86StdcallCallConv,
413-
Conv::X86ThisCall => llvm::X86_ThisCall,
414-
Conv::X86VectorCall => llvm::X86_VectorCall,
415-
Conv::X86_64SysV => llvm::X86_64_SysV,
416-
Conv::X86_64Win64 => llvm::X86_64_Win64,
417-
}
401+
self.conv.into()
418402
}
419403

420404
fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
@@ -596,3 +580,25 @@ impl<'tcx> AbiBuilderMethods<'tcx> for Builder<'_, '_, 'tcx> {
596580
llvm::get_param(self.llfn(), index as c_uint)
597581
}
598582
}
583+
584+
impl From<Conv> for llvm::CallConv {
585+
fn from(conv: Conv) -> Self {
586+
match conv {
587+
Conv::C | Conv::Rust | Conv::CCmseNonSecureCall => llvm::CCallConv,
588+
Conv::RustCold => llvm::ColdCallConv,
589+
Conv::AmdGpuKernel => llvm::AmdGpuKernel,
590+
Conv::AvrInterrupt => llvm::AvrInterrupt,
591+
Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
592+
Conv::ArmAapcs => llvm::ArmAapcsCallConv,
593+
Conv::Msp430Intr => llvm::Msp430Intr,
594+
Conv::PtxKernel => llvm::PtxKernel,
595+
Conv::X86Fastcall => llvm::X86FastcallCallConv,
596+
Conv::X86Intr => llvm::X86_Intr,
597+
Conv::X86Stdcall => llvm::X86StdcallCallConv,
598+
Conv::X86ThisCall => llvm::X86_ThisCall,
599+
Conv::X86VectorCall => llvm::X86_VectorCall,
600+
Conv::X86_64SysV => llvm::X86_64_SysV,
601+
Conv::X86_64Win64 => llvm::X86_64_Win64,
602+
}
603+
}
604+
}

Diff for: compiler/rustc_codegen_llvm/src/context.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -576,8 +576,14 @@ impl<'ll, 'tcx> MiscMethods<'tcx> for CodegenCx<'ll, 'tcx> {
576576
}
577577

578578
fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
579-
if self.get_declared_value("main").is_none() {
580-
Some(self.declare_cfn("main", llvm::UnnamedAddr::Global, fn_type))
579+
let entry_name = self.sess().target.entry_name.as_ref();
580+
if self.get_declared_value(entry_name).is_none() {
581+
Some(self.declare_entry_fn(
582+
entry_name,
583+
self.sess().target.entry_abi.into(),
584+
llvm::UnnamedAddr::Global,
585+
fn_type,
586+
))
581587
} else {
582588
// If the symbol already exists, it is an error: for example, the user wrote
583589
// #[no_mangle] extern "C" fn main(..) {..}

Diff for: compiler/rustc_codegen_llvm/src/declare.rs

+22
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,28 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
9090
declare_raw_fn(self, name, llvm::CCallConv, unnamed, visibility, fn_type)
9191
}
9292

93+
/// Declare an entry Function
94+
///
95+
/// The ABI of this function can change depending on the target (although for now the same as
96+
/// `declare_cfn`)
97+
///
98+
/// If there’s a value with the same name already declared, the function will
99+
/// update the declaration and return existing Value instead.
100+
pub fn declare_entry_fn(
101+
&self,
102+
name: &str,
103+
callconv: llvm::CallConv,
104+
unnamed: llvm::UnnamedAddr,
105+
fn_type: &'ll Type,
106+
) -> &'ll Value {
107+
let visibility = if self.tcx.sess.target.default_hidden_visibility {
108+
llvm::Visibility::Hidden
109+
} else {
110+
llvm::Visibility::Default
111+
};
112+
declare_raw_fn(self, name, callconv, unnamed, visibility, fn_type)
113+
}
114+
93115
/// Declare a Rust function.
94116
///
95117
/// If there’s a value with the same name already declared, the function will

Diff for: compiler/rustc_codegen_ssa/src/back/symbol_export.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,8 @@ fn exported_symbols_provider_local<'tcx>(
180180
.collect();
181181

182182
if tcx.entry_fn(()).is_some() {
183-
let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, "main"));
183+
let exported_symbol =
184+
ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
184185

185186
symbols.push((
186187
exported_symbol,

Diff for: compiler/rustc_target/src/abi/call/mod.rs

+28
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use crate::abi::{HasDataLayout, TyAbiInterface, TyAndLayout};
33
use crate::spec::{self, HasTargetSpec};
44
use rustc_span::Symbol;
55
use std::fmt;
6+
use std::str::FromStr;
67

78
mod aarch64;
89
mod amdgpu;
@@ -737,6 +738,33 @@ impl<'a, Ty> FnAbi<'a, Ty> {
737738
}
738739
}
739740

741+
impl FromStr for Conv {
742+
type Err = String;
743+
744+
fn from_str(s: &str) -> Result<Self, Self::Err> {
745+
match s {
746+
"C" => Ok(Conv::C),
747+
"Rust" => Ok(Conv::Rust),
748+
"RustCold" => Ok(Conv::Rust),
749+
"ArmAapcs" => Ok(Conv::ArmAapcs),
750+
"CCmseNonSecureCall" => Ok(Conv::CCmseNonSecureCall),
751+
"Msp430Intr" => Ok(Conv::Msp430Intr),
752+
"PtxKernel" => Ok(Conv::PtxKernel),
753+
"X86Fastcall" => Ok(Conv::X86Fastcall),
754+
"X86Intr" => Ok(Conv::X86Intr),
755+
"X86Stdcall" => Ok(Conv::X86Stdcall),
756+
"X86ThisCall" => Ok(Conv::X86ThisCall),
757+
"X86VectorCall" => Ok(Conv::X86VectorCall),
758+
"X86_64SysV" => Ok(Conv::X86_64SysV),
759+
"X86_64Win64" => Ok(Conv::X86_64Win64),
760+
"AmdGpuKernel" => Ok(Conv::AmdGpuKernel),
761+
"AvrInterrupt" => Ok(Conv::AvrInterrupt),
762+
"AvrNonBlockingInterrupt" => Ok(Conv::AvrNonBlockingInterrupt),
763+
_ => Err(format!("'{}' is not a valid value for entry function call convetion.", s)),
764+
}
765+
}
766+
}
767+
740768
// Some types are used a lot. Make sure they don't unintentionally get bigger.
741769
#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
742770
mod size_asserts {

Diff for: compiler/rustc_target/src/json.rs

+25
Original file line numberDiff line numberDiff line change
@@ -89,3 +89,28 @@ impl<A: ToJson> ToJson for Option<A> {
8989
}
9090
}
9191
}
92+
93+
impl ToJson for crate::abi::call::Conv {
94+
fn to_json(&self) -> Json {
95+
let s = match self {
96+
Self::C => "C",
97+
Self::Rust => "Rust",
98+
Self::RustCold => "RustCold",
99+
Self::ArmAapcs => "ArmAapcs",
100+
Self::CCmseNonSecureCall => "CCmseNonSecureCall",
101+
Self::Msp430Intr => "Msp430Intr",
102+
Self::PtxKernel => "PtxKernel",
103+
Self::X86Fastcall => "X86Fastcall",
104+
Self::X86Intr => "X86Intr",
105+
Self::X86Stdcall => "X86Stdcall",
106+
Self::X86ThisCall => "X86ThisCall",
107+
Self::X86VectorCall => "X86VectorCall",
108+
Self::X86_64SysV => "X86_64SysV",
109+
Self::X86_64Win64 => "X86_64Win64",
110+
Self::AmdGpuKernel => "AmdGpuKernel",
111+
Self::AvrInterrupt => "AvrInterrupt",
112+
Self::AvrNonBlockingInterrupt => "AvrNonBlockingInterrupt",
113+
};
114+
Json::String(s.to_owned())
115+
}
116+
}

Diff for: compiler/rustc_target/src/spec/mod.rs

+27
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
//! the target's settings, though `target-feature` and `link-args` will *add*
3535
//! to the list specified by the target, rather than replace.
3636
37+
use crate::abi::call::Conv;
3738
use crate::abi::Endian;
3839
use crate::json::{Json, ToJson};
3940
use crate::spec::abi::{lookup as lookup_abi, Abi};
@@ -1668,6 +1669,14 @@ pub struct TargetOptions {
16681669
/// Whether the target supports stack canary checks. `true` by default,
16691670
/// since this is most common among tier 1 and tier 2 targets.
16701671
pub supports_stack_protector: bool,
1672+
1673+
// The name of entry function.
1674+
// Default value is "main"
1675+
pub entry_name: StaticCow<str>,
1676+
1677+
// The ABI of entry function.
1678+
// Default value is `Conv::C`, i.e. C call convention
1679+
pub entry_abi: Conv,
16711680
}
16721681

16731682
/// Add arguments for the given flavor and also for its "twin" flavors
@@ -1884,6 +1893,8 @@ impl Default for TargetOptions {
18841893
c_enum_min_bits: 32,
18851894
generate_arange_section: true,
18861895
supports_stack_protector: true,
1896+
entry_name: "main".into(),
1897+
entry_abi: Conv::C,
18871898
}
18881899
}
18891900
}
@@ -2404,6 +2415,18 @@ impl Target {
24042415
}
24052416
}
24062417
} );
2418+
($key_name:ident, Conv) => ( {
2419+
let name = (stringify!($key_name)).replace("_", "-");
2420+
obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
2421+
match Conv::from_str(s) {
2422+
Ok(c) => {
2423+
base.$key_name = c;
2424+
Some(Ok(()))
2425+
}
2426+
Err(e) => Some(Err(e))
2427+
}
2428+
})).unwrap_or(Ok(()))
2429+
} );
24072430
}
24082431

24092432
if let Some(j) = obj.remove("target-endian") {
@@ -2523,6 +2546,8 @@ impl Target {
25232546
key!(c_enum_min_bits, u64);
25242547
key!(generate_arange_section, bool);
25252548
key!(supports_stack_protector, bool);
2549+
key!(entry_name);
2550+
key!(entry_abi, Conv)?;
25262551

25272552
if base.is_builtin {
25282553
// This can cause unfortunate ICEs later down the line.
@@ -2773,6 +2798,8 @@ impl ToJson for Target {
27732798
target_option_val!(c_enum_min_bits);
27742799
target_option_val!(generate_arange_section);
27752800
target_option_val!(supports_stack_protector);
2801+
target_option_val!(entry_name);
2802+
target_option_val!(entry_abi);
27762803

27772804
if let Some(abi) = self.default_adjusted_cabi {
27782805
d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());

0 commit comments

Comments
 (0)