]> git.lizzy.rs Git - rust.git/blobdiff - compiler/rustc_middle/src/ty/cast.rs
Auto merge of #107618 - chriswailes:linker-arg, r=albertlarsan68
[rust.git] / compiler / rustc_middle / src / ty / cast.rs
index 981e2d3b6d2d3ea952bb49c047ea9c792985698d..e65585955199fcc803d29913b879656af360b920 100644 (file)
@@ -2,6 +2,7 @@
 // typeck and codegen.
 
 use crate::ty::{self, Ty};
+use rustc_middle::mir;
 
 use rustc_macros::HashStable;
 
@@ -38,7 +39,7 @@ pub enum CastTy<'tcx> {
 }
 
 /// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html)
-/// (or librustc_typeck/check/cast.rs).
+/// (or rustc_hir_analysis/check/cast.rs).
 #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
 pub enum CastKind {
     CoercionCast,
@@ -75,3 +76,28 @@ pub fn from_ty(t: Ty<'tcx>) -> Option<CastTy<'tcx>> {
         }
     }
 }
+
+/// Returns `mir::CastKind` from the given parameters.
+pub fn mir_cast_kind<'tcx>(from_ty: Ty<'tcx>, cast_ty: Ty<'tcx>) -> mir::CastKind {
+    let from = CastTy::from_ty(from_ty);
+    let cast = CastTy::from_ty(cast_ty);
+    let cast_kind = match (from, cast) {
+        (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Int(_))) => {
+            mir::CastKind::PointerExposeAddress
+        }
+        (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PointerFromExposedAddress,
+        (_, Some(CastTy::DynStar)) => mir::CastKind::DynStar,
+        (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => mir::CastKind::IntToInt,
+        (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => mir::CastKind::FnPtrToPtr,
+
+        (Some(CastTy::Float), Some(CastTy::Int(_))) => mir::CastKind::FloatToInt,
+        (Some(CastTy::Int(_)), Some(CastTy::Float)) => mir::CastKind::IntToFloat,
+        (Some(CastTy::Float), Some(CastTy::Float)) => mir::CastKind::FloatToFloat,
+        (Some(CastTy::Ptr(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PtrToPtr,
+
+        (_, _) => {
+            bug!("Attempting to cast non-castable types {:?} and {:?}", from_ty, cast_ty)
+        }
+    };
+    cast_kind
+}