1 //! Codegen vtables and vtable accesses.
3 //! See `rustc_codegen_ssa/src/meth.rs` for reference.
4 // FIXME dedup this logic between miri, cg_llvm and cg_clif
7 use super::constant::pointer_for_allocation;
9 fn vtable_memflags() -> MemFlags {
10 let mut flags = MemFlags::trusted(); // A vtable access is always aligned and will never trap.
11 flags.set_readonly(); // A vtable is always read-only.
15 pub(crate) fn drop_fn_of_obj(fx: &mut FunctionCx<'_, '_, '_>, vtable: Value) -> Value {
16 let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
21 (ty::COMMON_VTABLE_ENTRIES_DROPINPLACE * usize_size) as i32,
25 pub(crate) fn size_of_obj(fx: &mut FunctionCx<'_, '_, '_>, vtable: Value) -> Value {
26 let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
31 (ty::COMMON_VTABLE_ENTRIES_SIZE * usize_size) as i32,
35 pub(crate) fn min_align_of_obj(fx: &mut FunctionCx<'_, '_, '_>, vtable: Value) -> Value {
36 let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
41 (ty::COMMON_VTABLE_ENTRIES_SIZE * usize_size) as i32,
45 pub(crate) fn get_ptr_and_method_ref<'tcx>(
46 fx: &mut FunctionCx<'_, '_, 'tcx>,
50 let (ptr, vtable) = if let Abi::ScalarPair(_, _) = arg.layout().abi {
51 arg.load_scalar_pair(fx)
53 let (ptr, vtable) = arg.try_to_ptr().unwrap();
54 (ptr.get_addr(fx), vtable.unwrap())
57 let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes();
58 let func_ref = fx.bcx.ins().load(
62 (idx * usize_size as usize) as i32,
67 pub(crate) fn get_vtable<'tcx>(
68 fx: &mut FunctionCx<'_, '_, 'tcx>,
70 trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
72 let vtable_ptr = if let Some(vtable_ptr) = fx.vtables.get(&(ty, trait_ref)) {
75 let vtable_alloc_id = match fx.tcx.vtable_allocation(ty, trait_ref) {
77 Err(_) => fx.tcx.sess().fatal("allocation of constant vtable failed"),
79 let vtable_allocation = fx.tcx.global_alloc(vtable_alloc_id).unwrap_memory();
80 let vtable_ptr = pointer_for_allocation(fx, vtable_allocation);
82 fx.vtables.insert((ty, trait_ref), vtable_ptr);
86 vtable_ptr.get_addr(fx)