rustc_codegen_llvm/
type_.rs

1use std::borrow::Borrow;
2use std::hash::{Hash, Hasher};
3use std::{fmt, ptr};
4
5use libc::c_uint;
6use rustc_abi::{AddressSpace, Align, Integer, Reg, Size};
7use rustc_codegen_ssa::common::TypeKind;
8use rustc_codegen_ssa::traits::*;
9use rustc_data_structures::small_c_str::SmallCStr;
10use rustc_middle::bug;
11use rustc_middle::ty::layout::TyAndLayout;
12use rustc_middle::ty::{self, Ty};
13use rustc_target::callconv::{CastTarget, FnAbi};
14
15use crate::abi::{FnAbiLlvmExt, LlvmType};
16use crate::common;
17use crate::context::{CodegenCx, GenericCx, SCx};
18use crate::llvm::{self, FALSE, Metadata, TRUE, ToLlvmBool, Type, Value};
19use crate::type_of::LayoutLlvmExt;
20
21impl PartialEq for Type {
22    fn eq(&self, other: &Self) -> bool {
23        ptr::eq(self, other)
24    }
25}
26
27impl Eq for Type {}
28
29impl Hash for Type {
30    fn hash<H: Hasher>(&self, state: &mut H) {
31        ptr::hash(self, state);
32    }
33}
34
35impl fmt::Debug for Type {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.write_str(
38            &llvm::build_string(|s| unsafe {
39                llvm::LLVMRustWriteTypeToString(self, s);
40            })
41            .expect("non-UTF8 type description from LLVM"),
42        )
43    }
44}
45
46impl<'ll> CodegenCx<'ll, '_> {}
47impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
48    pub(crate) fn type_named_struct(&self, name: &str) -> &'ll Type {
49        let name = SmallCStr::new(name);
50        unsafe { llvm::LLVMStructCreateNamed(self.llcx(), name.as_ptr()) }
51    }
52
53    pub(crate) fn set_struct_body(&self, ty: &'ll Type, els: &[&'ll Type], packed: bool) {
54        unsafe {
55            llvm::LLVMStructSetBody(ty, els.as_ptr(), els.len() as c_uint, packed.to_llvm_bool())
56        }
57    }
58    pub(crate) fn type_void(&self) -> &'ll Type {
59        unsafe { llvm::LLVMVoidTypeInContext(self.llcx()) }
60    }
61
62    ///x Creates an integer type with the given number of bits, e.g., i24
63    pub(crate) fn type_ix(&self, num_bits: u64) -> &'ll Type {
64        llvm::LLVMIntTypeInContext(self.llcx(), num_bits as c_uint)
65    }
66
67    pub(crate) fn type_vector(&self, ty: &'ll Type, len: u64) -> &'ll Type {
68        unsafe { llvm::LLVMVectorType(ty, len as c_uint) }
69    }
70
71    pub(crate) fn add_func(&self, name: &str, ty: &'ll Type) -> &'ll Value {
72        let name = SmallCStr::new(name);
73        unsafe { llvm::LLVMAddFunction(self.llmod(), name.as_ptr(), ty) }
74    }
75
76    pub(crate) fn func_params_types(&self, ty: &'ll Type) -> Vec<&'ll Type> {
77        unsafe {
78            let n_args = llvm::LLVMCountParamTypes(ty) as usize;
79            let mut args = Vec::with_capacity(n_args);
80            llvm::LLVMGetParamTypes(ty, args.as_mut_ptr());
81            args.set_len(n_args);
82            args
83        }
84    }
85}
86impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> {
87    pub(crate) fn type_bool(&self) -> &'ll Type {
88        self.type_i8()
89    }
90
91    pub(crate) fn type_int_from_ty(&self, t: ty::IntTy) -> &'ll Type {
92        match t {
93            ty::IntTy::Isize => self.type_isize(),
94            ty::IntTy::I8 => self.type_i8(),
95            ty::IntTy::I16 => self.type_i16(),
96            ty::IntTy::I32 => self.type_i32(),
97            ty::IntTy::I64 => self.type_i64(),
98            ty::IntTy::I128 => self.type_i128(),
99        }
100    }
101
102    pub(crate) fn type_uint_from_ty(&self, t: ty::UintTy) -> &'ll Type {
103        match t {
104            ty::UintTy::Usize => self.type_isize(),
105            ty::UintTy::U8 => self.type_i8(),
106            ty::UintTy::U16 => self.type_i16(),
107            ty::UintTy::U32 => self.type_i32(),
108            ty::UintTy::U64 => self.type_i64(),
109            ty::UintTy::U128 => self.type_i128(),
110        }
111    }
112
113    pub(crate) fn type_float_from_ty(&self, t: ty::FloatTy) -> &'ll Type {
114        match t {
115            ty::FloatTy::F16 => self.type_f16(),
116            ty::FloatTy::F32 => self.type_f32(),
117            ty::FloatTy::F64 => self.type_f64(),
118            ty::FloatTy::F128 => self.type_f128(),
119        }
120    }
121
122    /// Return an LLVM type that has at most the required alignment,
123    /// and exactly the required size, as a best-effort padding array.
124    pub(crate) fn type_padding_filler(&self, size: Size, align: Align) -> &'ll Type {
125        let unit = Integer::approximate_align(self, align);
126        let size = size.bytes();
127        let unit_size = unit.size().bytes();
128        assert_eq!(size % unit_size, 0);
129        self.type_array(self.type_from_integer(unit), size / unit_size)
130    }
131}
132
133impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
134    pub(crate) fn llcx(&self) -> &'ll llvm::Context {
135        (**self).borrow().llcx
136    }
137
138    pub(crate) fn llmod(&self) -> &'ll llvm::Module {
139        (**self).borrow().llmod
140    }
141
142    pub(crate) fn isize_ty(&self) -> &'ll Type {
143        (**self).borrow().isize_ty
144    }
145
146    pub(crate) fn type_variadic_func(&self, args: &[&'ll Type], ret: &'ll Type) -> &'ll Type {
147        unsafe { llvm::LLVMFunctionType(ret, args.as_ptr(), args.len() as c_uint, TRUE) }
148    }
149
150    pub(crate) fn type_i1(&self) -> &'ll Type {
151        unsafe { llvm::LLVMInt1TypeInContext(self.llcx()) }
152    }
153
154    pub(crate) fn type_struct(&self, els: &[&'ll Type], packed: bool) -> &'ll Type {
155        unsafe {
156            llvm::LLVMStructTypeInContext(
157                self.llcx(),
158                els.as_ptr(),
159                els.len() as c_uint,
160                packed.to_llvm_bool(),
161            )
162        }
163    }
164}
165
166impl<'ll, CX: Borrow<SCx<'ll>>> BaseTypeCodegenMethods for GenericCx<'ll, CX> {
167    fn type_i8(&self) -> &'ll Type {
168        unsafe { llvm::LLVMInt8TypeInContext(self.llcx()) }
169    }
170
171    fn type_i16(&self) -> &'ll Type {
172        unsafe { llvm::LLVMInt16TypeInContext(self.llcx()) }
173    }
174
175    fn type_i32(&self) -> &'ll Type {
176        unsafe { llvm::LLVMInt32TypeInContext(self.llcx()) }
177    }
178
179    fn type_i64(&self) -> &'ll Type {
180        unsafe { llvm::LLVMInt64TypeInContext(self.llcx()) }
181    }
182
183    fn type_i128(&self) -> &'ll Type {
184        self.type_ix(128)
185    }
186
187    fn type_isize(&self) -> &'ll Type {
188        self.isize_ty()
189    }
190
191    fn type_f16(&self) -> &'ll Type {
192        unsafe { llvm::LLVMHalfTypeInContext(self.llcx()) }
193    }
194
195    fn type_f32(&self) -> &'ll Type {
196        unsafe { llvm::LLVMFloatTypeInContext(self.llcx()) }
197    }
198
199    fn type_f64(&self) -> &'ll Type {
200        unsafe { llvm::LLVMDoubleTypeInContext(self.llcx()) }
201    }
202
203    fn type_f128(&self) -> &'ll Type {
204        unsafe { llvm::LLVMFP128TypeInContext(self.llcx()) }
205    }
206
207    fn type_func(&self, args: &[&'ll Type], ret: &'ll Type) -> &'ll Type {
208        unsafe { llvm::LLVMFunctionType(ret, args.as_ptr(), args.len() as c_uint, FALSE) }
209    }
210
211    fn type_kind(&self, ty: &'ll Type) -> TypeKind {
212        llvm::LLVMGetTypeKind(ty).to_rust().to_generic()
213    }
214
215    fn type_ptr(&self) -> &'ll Type {
216        llvm_type_ptr(self.llcx())
217    }
218
219    fn type_ptr_ext(&self, address_space: AddressSpace) -> &'ll Type {
220        llvm_type_ptr_in_address_space(self.llcx(), address_space)
221    }
222
223    fn element_type(&self, ty: &'ll Type) -> &'ll Type {
224        match self.type_kind(ty) {
225            TypeKind::Array | TypeKind::Vector => unsafe { llvm::LLVMGetElementType(ty) },
226            TypeKind::Pointer => bug!("element_type is not supported for opaque pointers"),
227            other => bug!("element_type called on unsupported type {other:?}"),
228        }
229    }
230
231    fn vector_length(&self, ty: &'ll Type) -> usize {
232        unsafe { llvm::LLVMGetVectorSize(ty) as usize }
233    }
234
235    fn float_width(&self, ty: &'ll Type) -> usize {
236        match self.type_kind(ty) {
237            TypeKind::Half => 16,
238            TypeKind::Float => 32,
239            TypeKind::Double => 64,
240            TypeKind::X86_FP80 => 80,
241            TypeKind::FP128 | TypeKind::PPC_FP128 => 128,
242            other => bug!("llvm_float_width called on a non-float type {other:?}"),
243        }
244    }
245
246    fn int_width(&self, ty: &'ll Type) -> u64 {
247        unsafe { llvm::LLVMGetIntTypeWidth(ty) as u64 }
248    }
249
250    fn val_ty(&self, v: &'ll Value) -> &'ll Type {
251        common::val_ty(v)
252    }
253
254    fn type_array(&self, ty: &'ll Type, len: u64) -> &'ll Type {
255        unsafe { llvm::LLVMArrayType2(ty, len) }
256    }
257}
258
259pub(crate) fn llvm_type_ptr(llcx: &llvm::Context) -> &Type {
260    llvm_type_ptr_in_address_space(llcx, AddressSpace::ZERO)
261}
262
263pub(crate) fn llvm_type_ptr_in_address_space<'ll>(
264    llcx: &'ll llvm::Context,
265    addr_space: AddressSpace,
266) -> &'ll Type {
267    llvm::LLVMPointerTypeInContext(llcx, addr_space.0)
268}
269
270impl<'ll, 'tcx> LayoutTypeCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
271    fn backend_type(&self, layout: TyAndLayout<'tcx>) -> &'ll Type {
272        layout.llvm_type(self)
273    }
274    fn immediate_backend_type(&self, layout: TyAndLayout<'tcx>) -> &'ll Type {
275        layout.immediate_llvm_type(self)
276    }
277    fn is_backend_immediate(&self, layout: TyAndLayout<'tcx>) -> bool {
278        layout.is_llvm_immediate()
279    }
280    fn is_backend_scalar_pair(&self, layout: TyAndLayout<'tcx>) -> bool {
281        layout.is_llvm_scalar_pair()
282    }
283    fn scalar_pair_element_backend_type(
284        &self,
285        layout: TyAndLayout<'tcx>,
286        index: usize,
287        immediate: bool,
288    ) -> &'ll Type {
289        layout.scalar_pair_element_llvm_type(self, index, immediate)
290    }
291    fn cast_backend_type(&self, ty: &CastTarget) -> &'ll Type {
292        ty.llvm_type(self)
293    }
294    fn fn_decl_backend_type(&self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
295        fn_abi.llvm_type(self)
296    }
297    fn fn_ptr_backend_type(&self, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
298        fn_abi.ptr_to_llvm_type(self)
299    }
300    fn reg_backend_type(&self, ty: &Reg) -> &'ll Type {
301        ty.llvm_type(self)
302    }
303}
304
305impl<'ll, 'tcx> TypeMembershipCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
306    fn add_type_metadata(&self, function: &'ll Value, typeid: &[u8]) {
307        let typeid_metadata = self.create_metadata(typeid);
308        let v = [llvm::LLVMValueAsMetadata(self.const_usize(0)), typeid_metadata];
309        self.global_add_metadata_node(function, llvm::MD_type, &v);
310    }
311
312    fn set_type_metadata(&self, function: &'ll Value, typeid: &[u8]) {
313        let typeid_metadata = self.create_metadata(typeid);
314        let v = [llvm::LLVMValueAsMetadata(self.const_usize(0)), typeid_metadata];
315        self.global_set_metadata_node(function, llvm::MD_type, &v);
316    }
317
318    fn typeid_metadata(&self, typeid: &[u8]) -> Option<&'ll Metadata> {
319        Some(self.create_metadata(typeid))
320    }
321
322    fn add_kcfi_type_metadata(&self, function: &'ll Value, kcfi_typeid: u32) {
323        let kcfi_type_metadata = [llvm::LLVMValueAsMetadata(self.const_u32(kcfi_typeid))];
324        self.global_add_metadata_node(function, llvm::MD_kcfi_type, &kcfi_type_metadata);
325    }
326
327    fn set_kcfi_type_metadata(&self, function: &'ll Value, kcfi_typeid: u32) {
328        let kcfi_type_metadata = [llvm::LLVMValueAsMetadata(self.const_u32(kcfi_typeid))];
329        self.global_set_metadata_node(function, llvm::MD_kcfi_type, &kcfi_type_metadata);
330    }
331}