]> git.lizzy.rs Git - rust.git/blob - src/vtable.rs
Rustup to rustc 1.55.0-nightly (6d820866a 2021-06-29)
[rust.git] / src / vtable.rs
1 //! Codegen vtables and vtable accesses.
2 //!
3 //! See `rustc_codegen_ssa/src/meth.rs` for reference.
4
5 use super::constant::pointer_for_allocation;
6 use crate::prelude::*;
7
8 fn vtable_memflags() -> MemFlags {
9     let mut flags = MemFlags::trusted(); // A vtable access is always aligned and will never trap.
10     flags.set_readonly(); // A vtable is always read-only.
11     flags
12 }
13
14 pub(crate) fn drop_fn_of_obj(fx: &mut FunctionCx<'_, '_, '_>, vtable: Value) -> Value {
15     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
16     fx.bcx.ins().load(
17         pointer_ty(fx.tcx),
18         vtable_memflags(),
19         vtable,
20         (ty::COMMON_VTABLE_ENTRIES_DROPINPLACE * usize_size) as i32,
21     )
22 }
23
24 pub(crate) fn size_of_obj(fx: &mut FunctionCx<'_, '_, '_>, vtable: Value) -> Value {
25     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
26     fx.bcx.ins().load(
27         pointer_ty(fx.tcx),
28         vtable_memflags(),
29         vtable,
30         (ty::COMMON_VTABLE_ENTRIES_SIZE * usize_size) as i32,
31     )
32 }
33
34 pub(crate) fn min_align_of_obj(fx: &mut FunctionCx<'_, '_, '_>, vtable: Value) -> Value {
35     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
36     fx.bcx.ins().load(
37         pointer_ty(fx.tcx),
38         vtable_memflags(),
39         vtable,
40         (ty::COMMON_VTABLE_ENTRIES_ALIGN * usize_size) as i32,
41     )
42 }
43
44 pub(crate) fn get_ptr_and_method_ref<'tcx>(
45     fx: &mut FunctionCx<'_, '_, 'tcx>,
46     arg: CValue<'tcx>,
47     idx: usize,
48 ) -> (Value, Value) {
49     let (ptr, vtable) = if let Abi::ScalarPair(_, _) = arg.layout().abi {
50         arg.load_scalar_pair(fx)
51     } else {
52         let (ptr, vtable) = arg.try_to_ptr().unwrap();
53         (ptr.get_addr(fx), vtable.unwrap())
54     };
55
56     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes();
57     let func_ref = fx.bcx.ins().load(
58         pointer_ty(fx.tcx),
59         vtable_memflags(),
60         vtable,
61         (idx * usize_size as usize) as i32,
62     );
63     (ptr, func_ref)
64 }
65
66 pub(crate) fn get_vtable<'tcx>(
67     fx: &mut FunctionCx<'_, '_, 'tcx>,
68     ty: Ty<'tcx>,
69     trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
70 ) -> Value {
71     let vtable_alloc_id = fx.tcx.vtable_allocation(ty, trait_ref);
72     let vtable_allocation = fx.tcx.global_alloc(vtable_alloc_id).unwrap_memory();
73     let vtable_ptr = pointer_for_allocation(fx, vtable_allocation);
74
75     vtable_ptr.get_addr(fx)
76 }