rust/compiler/rustc_codegen_ssa/src/meth.rs

85 lines
2.8 KiB
Rust
Raw Normal View History

2019-02-09 08:31:47 -06:00
use crate::traits::*;
use rustc_middle::ty::{self, Ty};
use rustc_target::abi::call::FnAbi;
#[derive(Copy, Clone, Debug)]
pub struct VirtualIndex(u64);
impl<'a, 'tcx> VirtualIndex {
pub fn from_index(index: usize) -> Self {
VirtualIndex(index as u64)
}
pub fn get_fn<Bx: BuilderMethods<'a, 'tcx>>(
self,
bx: &mut Bx,
llvtable: Bx::Value,
fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
) -> Bx::Value {
// Load the data pointer from the object.
debug!("get_fn({:?}, {:?})", llvtable, self);
let llty = bx.fn_ptr_backend_type(fn_abi);
let llvtable = bx.pointercast(llvtable, bx.type_ptr_to(llty));
let ptr_align = bx.tcx().data_layout.pointer_align.abi;
let gep = bx.inbounds_gep(llty, llvtable, &[bx.const_usize(self.0)]);
let ptr = bx.load(llty, gep, ptr_align);
2018-01-04 23:12:32 -06:00
bx.nonnull_metadata(ptr);
// Vtable loads are invariant.
2018-01-04 23:12:32 -06:00
bx.set_invariant_load(ptr);
ptr
}
2018-09-14 10:48:57 -05:00
pub fn get_usize<Bx: BuilderMethods<'a, 'tcx>>(
self,
bx: &mut Bx,
llvtable: Bx::Value,
2018-09-14 10:48:57 -05:00
) -> Bx::Value {
// Load the data pointer from the object.
debug!("get_int({:?}, {:?})", llvtable, self);
let llty = bx.type_isize();
let llvtable = bx.pointercast(llvtable, bx.type_ptr_to(llty));
let usize_align = bx.tcx().data_layout.pointer_align.abi;
let gep = bx.inbounds_gep(llty, llvtable, &[bx.const_usize(self.0)]);
let ptr = bx.load(llty, gep, usize_align);
// Vtable loads are invariant.
2018-01-04 23:12:32 -06:00
bx.set_invariant_load(ptr);
ptr
}
}
2016-09-08 05:58:05 -05:00
/// Creates a dynamic vtable for the given type and vtable origin.
/// This is used only for objects.
///
2016-09-08 05:58:05 -05:00
/// The vtables are cached instead of created on every call.
///
/// The `trait_ref` encodes the erased self type. Hence if we are
/// making an object `Foo<dyn Trait>` from a value of type `Foo<T>`, then
/// `trait_ref` would map `T: Trait`.
2018-09-13 07:58:19 -05:00
pub fn get_vtable<'tcx, Cx: CodegenMethods<'tcx>>(
cx: &Cx,
ty: Ty<'tcx>,
trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
2018-09-13 07:58:19 -05:00
) -> Cx::Value {
let tcx = cx.tcx();
debug!("get_vtable(ty={:?}, trait_ref={:?})", ty, trait_ref);
// Check the cache.
2018-09-13 07:58:19 -05:00
if let Some(&val) = cx.vtables().borrow().get(&(ty, trait_ref)) {
return val;
}
let vtable_alloc_id = tcx.vtable_allocation((ty, trait_ref));
let vtable_allocation = tcx.global_alloc(vtable_alloc_id).unwrap_memory();
let vtable_const = cx.const_data_from_alloc(vtable_allocation);
let align = cx.data_layout().pointer_align.abi;
2018-09-10 09:28:47 -05:00
let vtable = cx.static_addr_of(vtable_const, align, Some("vtable"));
cx.create_vtable_metadata(ty, trait_ref, vtable);
2018-09-13 07:58:19 -05:00
cx.vtables().borrow_mut().insert((ty, trait_ref), vtable);
2014-04-10 06:04:45 -05:00
vtable
}