llir/types/
float.rs

1use llvm_sys::core::LLVMGetTypeKind;
2use llvm_sys::prelude::LLVMTypeRef;
3use llvm_sys::LLVMTypeKind;
4use std::marker::PhantomData;
5
6use crate::types::*;
7use crate::{FromLLVMType, TypeRef};
8
9/// The type kind for Float Type
10#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
11#[allow(non_camel_case_types)]
12pub enum FloatTypeKind {
13  /// 16-bit
14  Half,
15  /// 32-bit
16  Single,
17  /// 64-bit
18  Double,
19  /// 128-bit
20  FP128,
21  /// 80-bit for X86
22  X86_FP80,
23  /// 128-bit for Power PC
24  PPC_FP128,
25}
26
27impl FloatTypeKind {
28  /// Get the bit-width of that type kind
29  pub fn width(&self) -> u32 {
30    match self {
31      Self::Half => 16,
32      Self::Single => 32,
33      Self::Double => 64,
34      Self::FP128 => 128,
35      Self::X86_FP80 => 80,
36      Self::PPC_FP128 => 128,
37    }
38  }
39
40  pub(crate) fn from_llvm(tk: LLVMTypeKind) -> Option<Self> {
41    use FloatTypeKind::*;
42    use LLVMTypeKind::*;
43    match tk {
44      LLVMHalfTypeKind => Some(Half),
45      LLVMFloatTypeKind => Some(Single),
46      LLVMDoubleTypeKind => Some(Double),
47      LLVMFP128TypeKind => Some(FP128),
48      LLVMX86_FP80TypeKind => Some(X86_FP80),
49      LLVMPPC_FP128TypeKind => Some(PPC_FP128),
50      _ => None,
51    }
52  }
53}
54
55/// [Float Type](https://llvm.org/docs/LangRef.html#floating-point-types)
56#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
57pub struct FloatType<'ctx>(FloatTypeKind, LLVMTypeRef, PhantomData<&'ctx ()>);
58
59impl_send_sync!(FloatType);
60
61impl<'ctx> FloatType<'ctx> {
62  /// Get the kind
63  pub fn kind(&self) -> FloatTypeKind {
64    self.0
65  }
66
67  /// Get the bit-width for this float type
68  pub fn width(&self) -> u32 {
69    self.0.width()
70  }
71}
72
73impl<'ctx> AsType<'ctx> for FloatType<'ctx> {
74  fn as_type(&self) -> Type<'ctx> {
75    Type::Float(self.clone())
76  }
77}
78
79impl_positional_type_ref!(FloatType, 1);
80
81impl<'ctx> FromLLVMType for FloatType<'ctx> {
82  fn from_llvm(ptr: LLVMTypeRef) -> Self {
83    let kind = FloatTypeKind::from_llvm(unsafe { LLVMGetTypeKind(ptr) }).unwrap();
84    Self(kind, ptr, PhantomData)
85  }
86}