]> git.lizzy.rs Git - rust.git/blob - src/common.rs
Auto merge of #94690 - nnethercote:clarify-Layout-interning, r=fee1-dead
[rust.git] / src / common.rs
1 use std::convert::TryFrom;
2
3 use gccjit::LValue;
4 use gccjit::{Block, CType, RValue, Type, ToRValue};
5 use rustc_codegen_ssa::mir::place::PlaceRef;
6 use rustc_codegen_ssa::traits::{
7     BaseTypeMethods,
8     ConstMethods,
9     DerivedTypeMethods,
10     MiscMethods,
11     StaticMethods,
12 };
13 use rustc_middle::mir::Mutability;
14 use rustc_middle::ty::ScalarInt;
15 use rustc_middle::ty::layout::{TyAndLayout, LayoutOf};
16 use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar};
17 use rustc_span::Symbol;
18 use rustc_target::abi::{self, HasDataLayout, Pointer, Size};
19
20 use crate::consts::const_alloc_to_gcc;
21 use crate::context::CodegenCx;
22 use crate::type_of::LayoutGccExt;
23
24 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
25     pub fn const_bytes(&self, bytes: &[u8]) -> RValue<'gcc> {
26         bytes_in_context(self, bytes)
27     }
28
29     fn global_string(&self, string: &str) -> LValue<'gcc> {
30         // TODO(antoyo): handle non-null-terminated strings.
31         let string = self.context.new_string_literal(&*string);
32         let sym = self.generate_local_symbol_name("str");
33         let global = self.declare_private_global(&sym, self.val_ty(string));
34         global.global_set_initializer_rvalue(string);
35         global
36         // TODO(antoyo): set linkage.
37     }
38
39     pub fn inttoptr(&self, block: Block<'gcc>, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
40         let func = block.get_function();
41         let local = func.new_local(None, value.get_type(), "intLocal");
42         block.add_assignment(None, local, value);
43         let value_address = local.get_address(None);
44
45         let ptr = self.context.new_cast(None, value_address, dest_ty.make_pointer());
46         ptr.dereference(None).to_rvalue()
47     }
48
49     pub fn ptrtoint(&self, block: Block<'gcc>, value: RValue<'gcc>, dest_ty: Type<'gcc>) -> RValue<'gcc> {
50         // TODO(antoyo): when libgccjit allow casting from pointer to int, remove this.
51         let func = block.get_function();
52         let local = func.new_local(None, value.get_type(), "ptrLocal");
53         block.add_assignment(None, local, value);
54         let ptr_address = local.get_address(None);
55
56         let ptr = self.context.new_cast(None, ptr_address, dest_ty.make_pointer());
57         ptr.dereference(None).to_rvalue()
58     }
59 }
60
61 pub fn bytes_in_context<'gcc, 'tcx>(cx: &CodegenCx<'gcc, 'tcx>, bytes: &[u8]) -> RValue<'gcc> {
62     let context = &cx.context;
63     let byte_type = context.new_type::<u8>();
64     let typ = context.new_array_type(None, byte_type, bytes.len() as i32);
65     let elements: Vec<_> =
66         bytes.iter()
67         .map(|&byte| context.new_rvalue_from_int(byte_type, byte as i32))
68         .collect();
69     context.new_array_constructor(None, typ, &elements)
70 }
71
72 pub fn type_is_pointer<'gcc>(typ: Type<'gcc>) -> bool {
73     typ.get_pointee().is_some()
74 }
75
76 impl<'gcc, 'tcx> ConstMethods<'tcx> for CodegenCx<'gcc, 'tcx> {
77     fn const_null(&self, typ: Type<'gcc>) -> RValue<'gcc> {
78         if type_is_pointer(typ) {
79             self.context.new_null(typ)
80         }
81         else {
82             self.const_int(typ, 0)
83         }
84     }
85
86     fn const_undef(&self, typ: Type<'gcc>) -> RValue<'gcc> {
87         let local = self.current_func.borrow().expect("func")
88             .new_local(None, typ, "undefined");
89         if typ.is_struct().is_some() {
90             // NOTE: hack to workaround a limitation of the rustc API: see comment on
91             // CodegenCx.structs_as_pointer
92             let pointer = local.get_address(None);
93             self.structs_as_pointer.borrow_mut().insert(pointer);
94             pointer
95         }
96         else {
97             local.to_rvalue()
98         }
99     }
100
101     fn const_int(&self, typ: Type<'gcc>, int: i64) -> RValue<'gcc> {
102         self.context.new_rvalue_from_long(typ, i64::try_from(int).expect("i64::try_from"))
103     }
104
105     fn const_uint(&self, typ: Type<'gcc>, int: u64) -> RValue<'gcc> {
106         self.context.new_rvalue_from_long(typ, u64::try_from(int).expect("u64::try_from") as i64)
107     }
108
109     fn const_uint_big(&self, typ: Type<'gcc>, num: u128) -> RValue<'gcc> {
110         if num >> 64 != 0 {
111             // FIXME(antoyo): use a new function new_rvalue_from_unsigned_long()?
112             let low = self.context.new_rvalue_from_long(self.u64_type, num as u64 as i64);
113             let high = self.context.new_rvalue_from_long(typ, (num >> 64) as u64 as i64);
114
115             let sixty_four = self.context.new_rvalue_from_long(typ, 64);
116             (high << sixty_four) | self.context.new_cast(None, low, typ)
117         }
118         else if typ.is_i128(self) {
119             let num = self.context.new_rvalue_from_long(self.u64_type, num as u64 as i64);
120             self.context.new_cast(None, num, typ)
121         }
122         else {
123             self.context.new_rvalue_from_long(typ, num as u64 as i64)
124         }
125     }
126
127     fn const_bool(&self, val: bool) -> RValue<'gcc> {
128         self.const_uint(self.type_i1(), val as u64)
129     }
130
131     fn const_i32(&self, i: i32) -> RValue<'gcc> {
132         self.const_int(self.type_i32(), i as i64)
133     }
134
135     fn const_u32(&self, i: u32) -> RValue<'gcc> {
136         self.const_uint(self.type_u32(), i as u64)
137     }
138
139     fn const_u64(&self, i: u64) -> RValue<'gcc> {
140         self.const_uint(self.type_u64(), i)
141     }
142
143     fn const_usize(&self, i: u64) -> RValue<'gcc> {
144         let bit_size = self.data_layout().pointer_size.bits();
145         if bit_size < 64 {
146             // make sure it doesn't overflow
147             assert!(i < (1 << bit_size));
148         }
149
150         self.const_uint(self.usize_type, i)
151     }
152
153     fn const_u8(&self, _i: u8) -> RValue<'gcc> {
154         unimplemented!();
155     }
156
157     fn const_real(&self, _t: Type<'gcc>, _val: f64) -> RValue<'gcc> {
158         unimplemented!();
159     }
160
161     fn const_str(&self, s: Symbol) -> (RValue<'gcc>, RValue<'gcc>) {
162         let s_str = s.as_str();
163         let str_global = *self.const_str_cache.borrow_mut().entry(s).or_insert_with(|| {
164             self.global_string(s_str)
165         });
166         let len = s_str.len();
167         let cs = self.const_ptrcast(str_global.get_address(None),
168             self.type_ptr_to(self.layout_of(self.tcx.types.str_).gcc_type(self, true)),
169         );
170         (cs, self.const_usize(len as u64))
171     }
172
173     fn const_struct(&self, values: &[RValue<'gcc>], packed: bool) -> RValue<'gcc> {
174         let fields: Vec<_> = values.iter()
175             .map(|value| value.get_type())
176             .collect();
177         // TODO(antoyo): cache the type? It's anonymous, so probably not.
178         let typ = self.type_struct(&fields, packed);
179         let struct_type = typ.is_struct().expect("struct type");
180         self.context.new_struct_constructor(None, struct_type.as_type(), None, values)
181     }
182
183     fn const_to_opt_uint(&self, _v: RValue<'gcc>) -> Option<u64> {
184         // TODO(antoyo)
185         None
186     }
187
188     fn const_to_opt_u128(&self, _v: RValue<'gcc>, _sign_ext: bool) -> Option<u128> {
189         // TODO(antoyo)
190         None
191     }
192
193     fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, ty: Type<'gcc>) -> RValue<'gcc> {
194         let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() };
195         match cv {
196             Scalar::Int(ScalarInt::ZST) => {
197                 assert_eq!(0, layout.value.size(self).bytes());
198                 self.const_undef(self.type_ix(0))
199             }
200             Scalar::Int(int) => {
201                 let data = int.assert_bits(layout.value.size(self));
202
203                 // FIXME(antoyo): there's some issues with using the u128 code that follows, so hard-code
204                 // the paths for floating-point values.
205                 if ty == self.float_type {
206                     return self.context.new_rvalue_from_double(ty, f32::from_bits(data as u32) as f64);
207                 }
208                 else if ty == self.double_type {
209                     return self.context.new_rvalue_from_double(ty, f64::from_bits(data as u64));
210                 }
211
212                 let value = self.const_uint_big(self.type_ix(bitsize), data);
213                 if layout.value == Pointer {
214                     self.inttoptr(self.current_block.borrow().expect("block"), value, ty)
215                 } else {
216                     self.const_bitcast(value, ty)
217                 }
218             }
219             Scalar::Ptr(ptr, _size) => {
220                 let (alloc_id, offset) = ptr.into_parts();
221                 let base_addr =
222                     match self.tcx.global_alloc(alloc_id) {
223                         GlobalAlloc::Memory(alloc) => {
224                             let init = const_alloc_to_gcc(self, alloc);
225                             let alloc = alloc.inner();
226                             let value =
227                                 match alloc.mutability {
228                                     Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
229                                     _ => self.static_addr_of(init, alloc.align, None),
230                                 };
231                             if !self.sess().fewer_names() {
232                                 // TODO(antoyo): set value name.
233                             }
234                             value
235                         },
236                         GlobalAlloc::Function(fn_instance) => {
237                             self.get_fn_addr(fn_instance)
238                         },
239                         GlobalAlloc::Static(def_id) => {
240                             assert!(self.tcx.is_static(def_id));
241                             self.get_static(def_id).get_address(None)
242                         },
243                     };
244                 let ptr_type = base_addr.get_type();
245                 let base_addr = self.const_bitcast(base_addr, self.usize_type);
246                 let offset = self.context.new_rvalue_from_long(self.usize_type, offset.bytes() as i64);
247                 let ptr = self.const_bitcast(base_addr + offset, ptr_type);
248                 if layout.value != Pointer {
249                     self.const_bitcast(ptr.dereference(None).to_rvalue(), ty)
250                 }
251                 else {
252                     self.const_bitcast(ptr, ty)
253                 }
254             }
255         }
256     }
257
258     fn const_data_from_alloc(&self, alloc: ConstAllocation<'tcx>) -> Self::Value {
259         const_alloc_to_gcc(self, alloc)
260     }
261
262     fn from_const_alloc(&self, layout: TyAndLayout<'tcx>, alloc: ConstAllocation<'tcx>, offset: Size) -> PlaceRef<'tcx, RValue<'gcc>> {
263         assert_eq!(alloc.inner().align, layout.align.abi);
264         let ty = self.type_ptr_to(layout.gcc_type(self, true));
265         let value =
266             if layout.size == Size::ZERO {
267                 let value = self.const_usize(alloc.inner().align.bytes());
268                 self.context.new_cast(None, value, ty)
269             }
270             else {
271                 let init = const_alloc_to_gcc(self, alloc);
272                 let base_addr = self.static_addr_of(init, alloc.inner().align, None);
273
274                 let array = self.const_bitcast(base_addr, self.type_i8p());
275                 let value = self.context.new_array_access(None, array, self.const_usize(offset.bytes())).get_address(None);
276                 self.const_bitcast(value, ty)
277             };
278         PlaceRef::new_sized(value, layout)
279     }
280
281     fn const_ptrcast(&self, val: RValue<'gcc>, ty: Type<'gcc>) -> RValue<'gcc> {
282         self.context.new_cast(None, val, ty)
283     }
284 }
285
286 pub trait SignType<'gcc, 'tcx> {
287     fn is_signed(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
288     fn is_unsigned(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
289     fn to_signed(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc>;
290     fn to_unsigned(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc>;
291 }
292
293 impl<'gcc, 'tcx> SignType<'gcc, 'tcx> for Type<'gcc> {
294     fn is_signed(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
295         self.is_i8(cx) || self.is_i16(cx) || self.is_i32(cx) || self.is_i64(cx) || self.is_i128(cx)
296     }
297
298     fn is_unsigned(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
299         self.is_u8(cx) || self.is_u16(cx) || self.is_u32(cx) || self.is_u64(cx) || self.is_u128(cx)
300     }
301
302     fn to_signed(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc> {
303         if self.is_u8(cx) {
304             cx.i8_type
305         }
306         else if self.is_u16(cx) {
307             cx.i16_type
308         }
309         else if self.is_u32(cx) {
310             cx.i32_type
311         }
312         else if self.is_u64(cx) {
313             cx.i64_type
314         }
315         else if self.is_u128(cx) {
316             cx.i128_type
317         }
318         else {
319             self.clone()
320         }
321     }
322
323     fn to_unsigned(&self, cx: &CodegenCx<'gcc, 'tcx>) -> Type<'gcc> {
324         if self.is_i8(cx) {
325             cx.u8_type
326         }
327         else if self.is_i16(cx) {
328             cx.u16_type
329         }
330         else if self.is_i32(cx) {
331             cx.u32_type
332         }
333         else if self.is_i64(cx) {
334             cx.u64_type
335         }
336         else if self.is_i128(cx) {
337             cx.u128_type
338         }
339         else {
340             self.clone()
341         }
342     }
343 }
344
345 pub trait TypeReflection<'gcc, 'tcx>  {
346     fn is_uchar(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
347     fn is_ushort(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
348     fn is_uint(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
349     fn is_ulong(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
350     fn is_ulonglong(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
351
352     fn is_i8(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
353     fn is_u8(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
354     fn is_i16(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
355     fn is_u16(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
356     fn is_i32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
357     fn is_u32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
358     fn is_i64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
359     fn is_u64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
360     fn is_i128(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
361     fn is_u128(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
362
363     fn is_f32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
364     fn is_f64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool;
365 }
366
367 impl<'gcc, 'tcx> TypeReflection<'gcc, 'tcx> for Type<'gcc> {
368     fn is_uchar(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
369         self.unqualified() == cx.u8_type
370     }
371
372     fn is_ushort(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
373         self.unqualified() == cx.u16_type
374     }
375
376     fn is_uint(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
377         self.unqualified() == cx.uint_type
378     }
379
380     fn is_ulong(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
381         self.unqualified() == cx.ulong_type
382     }
383
384     fn is_ulonglong(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
385         self.unqualified() == cx.ulonglong_type
386     }
387
388     fn is_i8(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
389         self.unqualified() == cx.i8_type
390     }
391
392     fn is_u8(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
393         self.unqualified() == cx.u8_type
394     }
395
396     fn is_i16(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
397         self.unqualified() == cx.i16_type
398     }
399
400     fn is_u16(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
401         self.unqualified() == cx.u16_type
402     }
403
404     fn is_i32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
405         self.unqualified() == cx.i32_type
406     }
407
408     fn is_u32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
409         self.unqualified() == cx.u32_type
410     }
411
412     fn is_i64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
413         self.unqualified() == cx.i64_type
414     }
415
416     fn is_u64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
417         self.unqualified() == cx.u64_type
418     }
419
420     fn is_i128(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
421         self.unqualified() == cx.context.new_c_type(CType::Int128t)
422     }
423
424     fn is_u128(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
425         self.unqualified() == cx.context.new_c_type(CType::UInt128t)
426     }
427
428     fn is_f32(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
429         self.unqualified() == cx.context.new_type::<f32>()
430     }
431
432     fn is_f64(&self, cx: &CodegenCx<'gcc, 'tcx>) -> bool {
433         self.unqualified() == cx.context.new_type::<f64>()
434     }
435 }