043436
From 9f0a8620bd7d325e6d42417b08daff3e55cb88f6 Mon Sep 17 00:00:00 2001
043436
From: Ayush Singh <ayushsingh1325@gmail.com>
043436
Date: Sat, 5 Nov 2022 14:36:38 +0530
043436
Subject: [PATCH] Improve generating Custom entry function
043436
043436
This commit is aimed at making compiler generated entry functions
043436
(Basically just C `main` right now) more generic so other targets can do
043436
similar things for custom entry. This was initially implemented as part
043436
of https://github.com/rust-lang/rust/pull/100316.
043436
043436
Currently, this moves the entry function name and Call convention to the
043436
target spec.
043436
043436
Signed-off-by: Ayush Singh <ayushsingh1325@gmail.com>
043436
---
043436
 compiler/rustc_codegen_llvm/src/abi.rs        | 40 +++++++++++--------
043436
 compiler/rustc_codegen_llvm/src/context.rs    | 10 ++++-
043436
 compiler/rustc_codegen_llvm/src/declare.rs    | 22 ++++++++++
043436
 .../src/back/symbol_export.rs                 |  3 +-
043436
 compiler/rustc_target/src/abi/call/mod.rs     | 28 +++++++++++++
043436
 compiler/rustc_target/src/json.rs             | 25 ++++++++++++
043436
 compiler/rustc_target/src/spec/mod.rs         | 27 +++++++++++++
043436
 7 files changed, 135 insertions(+), 20 deletions(-)
043436
043436
diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs
043436
index d478efc863a9..a6fd2a7de6bd 100644
043436
--- a/compiler/rustc_codegen_llvm/src/abi.rs
043436
+++ b/compiler/rustc_codegen_llvm/src/abi.rs
043436
@@ -398,23 +398,7 @@ fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
043436
     }
043436
 
043436
     fn llvm_cconv(&self) -> llvm::CallConv {
043436
-        match self.conv {
043436
-            Conv::C | Conv::Rust | Conv::CCmseNonSecureCall => llvm::CCallConv,
043436
-            Conv::RustCold => llvm::ColdCallConv,
043436
-            Conv::AmdGpuKernel => llvm::AmdGpuKernel,
043436
-            Conv::AvrInterrupt => llvm::AvrInterrupt,
043436
-            Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
043436
-            Conv::ArmAapcs => llvm::ArmAapcsCallConv,
043436
-            Conv::Msp430Intr => llvm::Msp430Intr,
043436
-            Conv::PtxKernel => llvm::PtxKernel,
043436
-            Conv::X86Fastcall => llvm::X86FastcallCallConv,
043436
-            Conv::X86Intr => llvm::X86_Intr,
043436
-            Conv::X86Stdcall => llvm::X86StdcallCallConv,
043436
-            Conv::X86ThisCall => llvm::X86_ThisCall,
043436
-            Conv::X86VectorCall => llvm::X86_VectorCall,
043436
-            Conv::X86_64SysV => llvm::X86_64_SysV,
043436
-            Conv::X86_64Win64 => llvm::X86_64_Win64,
043436
-        }
043436
+        self.conv.into()
043436
     }
043436
 
043436
     fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
043436
@@ -596,3 +580,25 @@ fn get_param(&mut self, index: usize) -> Self::Value {
043436
         llvm::get_param(self.llfn(), index as c_uint)
043436
     }
043436
 }
043436
+
043436
+impl From<Conv> for llvm::CallConv {
043436
+    fn from(conv: Conv) -> Self {
043436
+        match conv {
043436
+            Conv::C | Conv::Rust | Conv::CCmseNonSecureCall => llvm::CCallConv,
043436
+            Conv::RustCold => llvm::ColdCallConv,
043436
+            Conv::AmdGpuKernel => llvm::AmdGpuKernel,
043436
+            Conv::AvrInterrupt => llvm::AvrInterrupt,
043436
+            Conv::AvrNonBlockingInterrupt => llvm::AvrNonBlockingInterrupt,
043436
+            Conv::ArmAapcs => llvm::ArmAapcsCallConv,
043436
+            Conv::Msp430Intr => llvm::Msp430Intr,
043436
+            Conv::PtxKernel => llvm::PtxKernel,
043436
+            Conv::X86Fastcall => llvm::X86FastcallCallConv,
043436
+            Conv::X86Intr => llvm::X86_Intr,
043436
+            Conv::X86Stdcall => llvm::X86StdcallCallConv,
043436
+            Conv::X86ThisCall => llvm::X86_ThisCall,
043436
+            Conv::X86VectorCall => llvm::X86_VectorCall,
043436
+            Conv::X86_64SysV => llvm::X86_64_SysV,
043436
+            Conv::X86_64Win64 => llvm::X86_64_Win64,
043436
+        }
043436
+    }
043436
+}
043436
diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs
043436
index 79ddfd884dfa..f3ef618fff54 100644
043436
--- a/compiler/rustc_codegen_llvm/src/context.rs
043436
+++ b/compiler/rustc_codegen_llvm/src/context.rs
043436
@@ -570,8 +570,14 @@ fn apply_target_cpu_attr(&self, llfn: &'ll Value) {
043436
     }
043436
 
043436
     fn declare_c_main(&self, fn_type: Self::Type) -> Option<Self::Function> {
043436
-        if self.get_declared_value("main").is_none() {
043436
-            Some(self.declare_cfn("main", llvm::UnnamedAddr::Global, fn_type))
043436
+        let entry_name = self.sess().target.entry_name.as_ref();
043436
+        if self.get_declared_value(entry_name).is_none() {
043436
+            Some(self.declare_entry_fn(
043436
+                entry_name,
043436
+                self.sess().target.entry_abi.into(),
043436
+                llvm::UnnamedAddr::Global,
043436
+                fn_type,
043436
+            ))
043436
         } else {
043436
             // If the symbol already exists, it is an error: for example, the user wrote
043436
             // #[no_mangle] extern "C" fn main(..) {..}
043436
diff --git a/compiler/rustc_codegen_llvm/src/declare.rs b/compiler/rustc_codegen_llvm/src/declare.rs
043436
index f79ef11720df..dc21a02cec44 100644
043436
--- a/compiler/rustc_codegen_llvm/src/declare.rs
043436
+++ b/compiler/rustc_codegen_llvm/src/declare.rs
043436
@@ -90,6 +90,28 @@ pub fn declare_cfn(
043436
         declare_raw_fn(self, name, llvm::CCallConv, unnamed, visibility, fn_type)
043436
     }
043436
 
043436
+    /// Declare an entry Function
043436
+    ///
043436
+    /// The ABI of this function can change depending on the target (although for now the same as
043436
+    /// `declare_cfn`)
043436
+    ///
043436
+    /// If there’s a value with the same name already declared, the function will
043436
+    /// update the declaration and return existing Value instead.
043436
+    pub fn declare_entry_fn(
043436
+        &self,
043436
+        name: &str,
043436
+        callconv: llvm::CallConv,
043436
+        unnamed: llvm::UnnamedAddr,
043436
+        fn_type: &'ll Type,
043436
+    ) -> &'ll Value {
043436
+        let visibility = if self.tcx.sess.target.default_hidden_visibility {
043436
+            llvm::Visibility::Hidden
043436
+        } else {
043436
+            llvm::Visibility::Default
043436
+        };
043436
+        declare_raw_fn(self, name, callconv, unnamed, visibility, fn_type)
043436
+    }
043436
+
043436
     /// Declare a Rust function.
043436
     ///
043436
     /// If there’s a value with the same name already declared, the function will
043436
diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs
043436
index 752f6b1ef40c..22f534d909ab 100644
043436
--- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs
043436
+++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs
043436
@@ -180,7 +180,8 @@ fn exported_symbols_provider_local<'tcx>(
043436
         .collect();
043436
 
043436
     if tcx.entry_fn(()).is_some() {
043436
-        let exported_symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, "main"));
043436
+        let exported_symbol =
043436
+            ExportedSymbol::NoDefId(SymbolName::new(tcx, tcx.sess.target.entry_name.as_ref()));
043436
 
043436
         symbols.push((
043436
             exported_symbol,
043436
diff --git a/compiler/rustc_target/src/abi/call/mod.rs b/compiler/rustc_target/src/abi/call/mod.rs
043436
index 9e5f0e4d158b..c622bd36b00c 100644
043436
--- a/compiler/rustc_target/src/abi/call/mod.rs
043436
+++ b/compiler/rustc_target/src/abi/call/mod.rs
043436
@@ -3,6 +3,7 @@
043436
 use crate::spec::{self, HasTargetSpec};
043436
 use rustc_span::Symbol;
043436
 use std::fmt;
043436
+use std::str::FromStr;
043436
 
043436
 mod aarch64;
043436
 mod amdgpu;
043436
@@ -735,6 +736,33 @@ pub fn adjust_for_foreign_abi<C>(
043436
     }
043436
 }
043436
 
043436
+impl FromStr for Conv {
043436
+    type Err = String;
043436
+
043436
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
043436
+        match s {
043436
+            "C" => Ok(Conv::C),
043436
+            "Rust" => Ok(Conv::Rust),
043436
+            "RustCold" => Ok(Conv::Rust),
043436
+            "ArmAapcs" => Ok(Conv::ArmAapcs),
043436
+            "CCmseNonSecureCall" => Ok(Conv::CCmseNonSecureCall),
043436
+            "Msp430Intr" => Ok(Conv::Msp430Intr),
043436
+            "PtxKernel" => Ok(Conv::PtxKernel),
043436
+            "X86Fastcall" => Ok(Conv::X86Fastcall),
043436
+            "X86Intr" => Ok(Conv::X86Intr),
043436
+            "X86Stdcall" => Ok(Conv::X86Stdcall),
043436
+            "X86ThisCall" => Ok(Conv::X86ThisCall),
043436
+            "X86VectorCall" => Ok(Conv::X86VectorCall),
043436
+            "X86_64SysV" => Ok(Conv::X86_64SysV),
043436
+            "X86_64Win64" => Ok(Conv::X86_64Win64),
043436
+            "AmdGpuKernel" => Ok(Conv::AmdGpuKernel),
043436
+            "AvrInterrupt" => Ok(Conv::AvrInterrupt),
043436
+            "AvrNonBlockingInterrupt" => Ok(Conv::AvrNonBlockingInterrupt),
043436
+            _ => Err(format!("'{}' is not a valid value for entry function call convetion.", s)),
043436
+        }
043436
+    }
043436
+}
043436
+
043436
 // Some types are used a lot. Make sure they don't unintentionally get bigger.
043436
 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
043436
 mod size_asserts {
043436
diff --git a/compiler/rustc_target/src/json.rs b/compiler/rustc_target/src/json.rs
043436
index b5d926352122..75bb76a9de08 100644
043436
--- a/compiler/rustc_target/src/json.rs
043436
+++ b/compiler/rustc_target/src/json.rs
043436
@@ -89,3 +89,28 @@ fn to_json(&self) -> Json {
043436
         }
043436
     }
043436
 }
043436
+
043436
+impl ToJson for crate::abi::call::Conv {
043436
+    fn to_json(&self) -> Json {
043436
+        let s = match self {
043436
+            Self::C => "C",
043436
+            Self::Rust => "Rust",
043436
+            Self::RustCold => "RustCold",
043436
+            Self::ArmAapcs => "ArmAapcs",
043436
+            Self::CCmseNonSecureCall => "CCmseNonSecureCall",
043436
+            Self::Msp430Intr => "Msp430Intr",
043436
+            Self::PtxKernel => "PtxKernel",
043436
+            Self::X86Fastcall => "X86Fastcall",
043436
+            Self::X86Intr => "X86Intr",
043436
+            Self::X86Stdcall => "X86Stdcall",
043436
+            Self::X86ThisCall => "X86ThisCall",
043436
+            Self::X86VectorCall => "X86VectorCall",
043436
+            Self::X86_64SysV => "X86_64SysV",
043436
+            Self::X86_64Win64 => "X86_64Win64",
043436
+            Self::AmdGpuKernel => "AmdGpuKernel",
043436
+            Self::AvrInterrupt => "AvrInterrupt",
043436
+            Self::AvrNonBlockingInterrupt => "AvrNonBlockingInterrupt",
043436
+        };
043436
+        Json::String(s.to_owned())
043436
+    }
043436
+}
043436
diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs
043436
index 72b088d663b1..617de46a55aa 100644
043436
--- a/compiler/rustc_target/src/spec/mod.rs
043436
+++ b/compiler/rustc_target/src/spec/mod.rs
043436
@@ -34,6 +34,7 @@
043436
 //! the target's settings, though `target-feature` and `link-args` will *add*
043436
 //! to the list specified by the target, rather than replace.
043436
 
043436
+use crate::abi::call::Conv;
043436
 use crate::abi::Endian;
043436
 use crate::json::{Json, ToJson};
043436
 use crate::spec::abi::{lookup as lookup_abi, Abi};
043436
@@ -1668,6 +1669,14 @@ pub struct TargetOptions {
043436
     /// Whether the target supports stack canary checks. `true` by default,
043436
     /// since this is most common among tier 1 and tier 2 targets.
043436
     pub supports_stack_protector: bool,
043436
+
043436
+    // The name of entry function.
043436
+    // Default value is "main"
043436
+    pub entry_name: StaticCow<str>,
043436
+
043436
+    // The ABI of entry function.
043436
+    // Default value is `Conv::C`, i.e. C call convention
043436
+    pub entry_abi: Conv,
043436
 }
043436
 
043436
 /// Add arguments for the given flavor and also for its "twin" flavors
043436
@@ -1884,6 +1893,8 @@ fn default() -> TargetOptions {
043436
             c_enum_min_bits: 32,
043436
             generate_arange_section: true,
043436
             supports_stack_protector: true,
043436
+            entry_name: "main".into(),
043436
+            entry_abi: Conv::C,
043436
         }
043436
     }
043436
 }
043436
@@ -2401,6 +2412,18 @@ macro_rules! key {
043436
                     }
043436
                 }
043436
             } );
043436
+            ($key_name:ident, Conv) => ( {
043436
+                let name = (stringify!($key_name)).replace("_", "-");
043436
+                obj.remove(&name).and_then(|o| o.as_str().and_then(|s| {
043436
+                    match Conv::from_str(s) {
043436
+                        Ok(c) => {
043436
+                            base.$key_name = c;
043436
+                            Some(Ok(()))
043436
+                        }
043436
+                        Err(e) => Some(Err(e))
043436
+                    }
043436
+                })).unwrap_or(Ok(()))
043436
+            } );
043436
         }
043436
 
043436
         if let Some(j) = obj.remove("target-endian") {
043436
@@ -2520,6 +2543,8 @@ macro_rules! key {
043436
         key!(c_enum_min_bits, u64);
043436
         key!(generate_arange_section, bool);
043436
         key!(supports_stack_protector, bool);
043436
+        key!(entry_name);
043436
+        key!(entry_abi, Conv)?;
043436
 
043436
         if base.is_builtin {
043436
             // This can cause unfortunate ICEs later down the line.
043436
@@ -2770,6 +2795,8 @@ macro_rules! target_option_val {
043436
         target_option_val!(c_enum_min_bits);
043436
         target_option_val!(generate_arange_section);
043436
         target_option_val!(supports_stack_protector);
043436
+        target_option_val!(entry_name);
043436
+        target_option_val!(entry_abi);
043436
 
043436
         if let Some(abi) = self.default_adjusted_cabi {
043436
             d.insert("default-adjusted-cabi".into(), Abi::name(abi).to_json());
043436
-- 
043436
2.38.1
043436