]> git.lizzy.rs Git - rust.git/blob - src/vtable.rs
Remove byteorder dependency
[rust.git] / src / vtable.rs
1 //! See librustc_codegen_llvm/meth.rs for reference
2
3 use crate::prelude::*;
4
5 const DROP_FN_INDEX: usize = 0;
6 const SIZE_INDEX: usize = 1;
7 const ALIGN_INDEX: usize = 2;
8
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.
12     flags
13 }
14
15 pub(crate) fn drop_fn_of_obj(fx: &mut FunctionCx<'_, '_, impl Backend>, vtable: Value) -> Value {
16     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
17     fx.bcx.ins().load(
18         pointer_ty(fx.tcx),
19         vtable_memflags(),
20         vtable,
21         (DROP_FN_INDEX * usize_size) as i32,
22     )
23 }
24
25 pub(crate) fn size_of_obj(fx: &mut FunctionCx<'_, '_, impl Backend>, vtable: Value) -> Value {
26     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
27     fx.bcx.ins().load(
28         pointer_ty(fx.tcx),
29         vtable_memflags(),
30         vtable,
31         (SIZE_INDEX * usize_size) as i32,
32     )
33 }
34
35 pub(crate) fn min_align_of_obj(fx: &mut FunctionCx<'_, '_, impl Backend>, vtable: Value) -> Value {
36     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
37     fx.bcx.ins().load(
38         pointer_ty(fx.tcx),
39         vtable_memflags(),
40         vtable,
41         (ALIGN_INDEX * usize_size) as i32,
42     )
43 }
44
45 pub(crate) fn get_ptr_and_method_ref<'tcx>(
46     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
47     arg: CValue<'tcx>,
48     idx: usize,
49 ) -> (Value, Value) {
50     let (ptr, vtable) = if let Abi::ScalarPair(_, _) = arg.layout().abi {
51         arg.load_scalar_pair(fx)
52     } else {
53         let (ptr, vtable) = arg.try_to_ptr().unwrap();
54         (ptr.get_addr(fx), vtable.unwrap())
55     };
56
57     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes();
58     let func_ref = fx.bcx.ins().load(
59         pointer_ty(fx.tcx),
60         vtable_memflags(),
61         vtable,
62         ((idx + 3) * usize_size as usize) as i32,
63     );
64     (ptr, func_ref)
65 }
66
67 pub(crate) fn get_vtable<'tcx>(
68     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
69     layout: TyAndLayout<'tcx>,
70     trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
71 ) -> Value {
72     let data_id = if let Some(data_id) = fx.cx.vtables.get(&(layout.ty, trait_ref)) {
73         *data_id
74     } else {
75         let data_id = build_vtable(fx, layout, trait_ref);
76         fx.cx.vtables.insert((layout.ty, trait_ref), data_id);
77         data_id
78     };
79
80     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
81     fx.bcx.ins().global_value(fx.pointer_type, local_data_id)
82 }
83
84 fn build_vtable<'tcx>(
85     fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
86     layout: TyAndLayout<'tcx>,
87     trait_ref: Option<ty::PolyExistentialTraitRef<'tcx>>,
88 ) -> DataId {
89     let tcx = fx.tcx;
90     let usize_size = fx.layout_of(fx.tcx.types.usize).size.bytes() as usize;
91
92     let drop_in_place_fn = import_function(
93         tcx,
94         &mut fx.cx.module,
95         Instance::resolve_drop_in_place(tcx, layout.ty).polymorphize(fx.tcx),
96     );
97
98     let mut components: Vec<_> = vec![Some(drop_in_place_fn), None, None];
99
100     let methods_root;
101     let methods = if let Some(trait_ref) = trait_ref {
102         methods_root = tcx.vtable_methods(trait_ref.with_self_ty(tcx, layout.ty));
103         methods_root.iter()
104     } else {
105         (&[]).iter()
106     };
107     let methods = methods.cloned().map(|opt_mth| {
108         opt_mth.map_or(None, |(def_id, substs)| {
109             Some(import_function(
110                 tcx,
111                 &mut fx.cx.module,
112                 Instance::resolve_for_vtable(tcx, ParamEnv::reveal_all(), def_id, substs)
113                     .unwrap()
114                     .polymorphize(fx.tcx),
115             ))
116         })
117     });
118     components.extend(methods);
119
120     let mut data_ctx = DataContext::new();
121     let mut data = ::std::iter::repeat(0u8)
122         .take(components.len() * usize_size)
123         .collect::<Vec<u8>>()
124         .into_boxed_slice();
125
126     write_usize(fx.tcx, &mut data, SIZE_INDEX, layout.size.bytes());
127     write_usize(fx.tcx, &mut data, ALIGN_INDEX, layout.align.abi.bytes());
128     data_ctx.define(data);
129
130     for (i, component) in components.into_iter().enumerate() {
131         if let Some(func_id) = component {
132             let func_ref = fx.cx.module.declare_func_in_data(func_id, &mut data_ctx);
133             data_ctx.write_function_addr((i * usize_size) as u32, func_ref);
134         }
135     }
136
137     let data_id = fx
138         .cx
139         .module
140         .declare_data(
141             &format!(
142                 "__vtable.{}.for.{:?}.{}",
143                 trait_ref
144                     .as_ref()
145                     .map(|trait_ref| format!("{:?}", trait_ref.skip_binder()).into())
146                     .unwrap_or(std::borrow::Cow::Borrowed("???")),
147                 layout.ty,
148                 fx.cx.vtables.len(),
149             ),
150             Linkage::Local,
151             false,
152             false,
153             Some(
154                 fx.tcx
155                     .data_layout
156                     .pointer_align
157                     .pref
158                     .bytes()
159                     .try_into()
160                     .unwrap(),
161             ),
162         )
163         .unwrap();
164
165     fx.cx.module.define_data(data_id, &data_ctx).unwrap();
166
167     data_id
168 }
169
170 fn write_usize(tcx: TyCtxt<'_>, buf: &mut [u8], idx: usize, num: u64) {
171     let pointer_size = tcx
172         .layout_of(ParamEnv::reveal_all().and(tcx.types.usize))
173         .unwrap()
174         .size
175         .bytes() as usize;
176     let target = &mut buf[idx * pointer_size..(idx + 1) * pointer_size];
177
178     match tcx.data_layout.endian {
179         rustc_target::abi::Endian::Little => match pointer_size {
180             4 => target.copy_from_slice(&(num as u32).to_le_bytes()),
181             8 => target.copy_from_slice(&(num as u64).to_le_bytes()),
182             _ => todo!("pointer size {} is not yet supported", pointer_size),
183         },
184         rustc_target::abi::Endian::Big => match pointer_size {
185             4 => target.copy_from_slice(&(num as u32).to_be_bytes()),
186             8 => target.copy_from_slice(&(num as u64).to_be_bytes()),
187             _ => todo!("pointer size {} is not yet supported", pointer_size),
188         },
189     }
190 }