]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/common.rs
Remove unused #[allow(...)] statements from compiler/
[rust.git] / compiler / rustc_codegen_llvm / src / common.rs
1 //! Code that is useful in various codegen modules.
2
3 use crate::consts::{self, const_alloc_to_llvm};
4 pub use crate::context::CodegenCx;
5 use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, OperandBundleDef, True};
6 use crate::type_::Type;
7 use crate::type_of::LayoutLlvmExt;
8 use crate::value::Value;
9
10 use rustc_ast::Mutability;
11 use rustc_codegen_ssa::mir::place::PlaceRef;
12 use rustc_codegen_ssa::traits::*;
13 use rustc_middle::bug;
14 use rustc_middle::mir::interpret::{Allocation, GlobalAlloc, Scalar};
15 use rustc_middle::ty::layout::TyAndLayout;
16 use rustc_span::symbol::Symbol;
17 use rustc_target::abi::{self, AddressSpace, HasDataLayout, LayoutOf, Pointer, Size};
18
19 use libc::{c_char, c_uint};
20 use tracing::debug;
21
22 /*
23 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
24 *
25 * An "extern" is an LLVM symbol we wind up emitting an undefined external
26 * reference to. This means "we don't have the thing in this compilation unit,
27 * please make sure you link it in at runtime". This could be a reference to
28 * C code found in a C library, or rust code found in a rust crate.
29 *
30 * Most "externs" are implicitly declared (automatically) as a result of a
31 * user declaring an extern _module_ dependency; this causes the rust driver
32 * to locate an extern crate, scan its compilation metadata, and emit extern
33 * declarations for any symbols used by the declaring crate.
34 *
35 * A "foreign" is an extern that references C (or other non-rust ABI) code.
36 * There is no metadata to scan for extern references so in these cases either
37 * a header-digester like bindgen, or manual function prototypes, have to
38 * serve as declarators. So these are usually given explicitly as prototype
39 * declarations, in rust code, with ABI attributes on them noting which ABI to
40 * link via.
41 *
42 * An "upcall" is a foreign call generated by the compiler (not corresponding
43 * to any user-written call in the code) into the runtime library, to perform
44 * some helper task such as bringing a task to life, allocating memory, etc.
45 *
46 */
47
48 /// A structure representing an active landing pad for the duration of a basic
49 /// block.
50 ///
51 /// Each `Block` may contain an instance of this, indicating whether the block
52 /// is part of a landing pad or not. This is used to make decision about whether
53 /// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
54 /// use `invoke`) and also about various function call metadata.
55 ///
56 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
57 /// just a bunch of `None` instances (not too interesting), but for MSVC
58 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
59 /// When inside of a landing pad, each function call in LLVM IR needs to be
60 /// annotated with which landing pad it's a part of. This is accomplished via
61 /// the `OperandBundleDef` value created for MSVC landing pads.
62 pub struct Funclet<'ll> {
63     cleanuppad: &'ll Value,
64     operand: OperandBundleDef<'ll>,
65 }
66
67 impl Funclet<'ll> {
68     pub fn new(cleanuppad: &'ll Value) -> Self {
69         Funclet { cleanuppad, operand: OperandBundleDef::new("funclet", &[cleanuppad]) }
70     }
71
72     pub fn cleanuppad(&self) -> &'ll Value {
73         self.cleanuppad
74     }
75
76     pub fn bundle(&self) -> &OperandBundleDef<'ll> {
77         &self.operand
78     }
79 }
80
81 impl BackendTypes for CodegenCx<'ll, 'tcx> {
82     type Value = &'ll Value;
83     type Function = &'ll Value;
84
85     type BasicBlock = &'ll BasicBlock;
86     type Type = &'ll Type;
87     type Funclet = Funclet<'ll>;
88
89     type DIScope = &'ll llvm::debuginfo::DIScope;
90     type DIVariable = &'ll llvm::debuginfo::DIVariable;
91 }
92
93 impl CodegenCx<'ll, 'tcx> {
94     pub fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
95         unsafe { llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint) }
96     }
97
98     pub fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
99         unsafe { llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint) }
100     }
101
102     pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
103         bytes_in_context(self.llcx, bytes)
104     }
105
106     fn const_cstr(&self, s: Symbol, null_terminated: bool) -> &'ll Value {
107         unsafe {
108             if let Some(&llval) = self.const_cstr_cache.borrow().get(&s) {
109                 return llval;
110             }
111
112             let s_str = s.as_str();
113             let sc = llvm::LLVMConstStringInContext(
114                 self.llcx,
115                 s_str.as_ptr() as *const c_char,
116                 s_str.len() as c_uint,
117                 !null_terminated as Bool,
118             );
119             let sym = self.generate_local_symbol_name("str");
120             let g = self.define_global(&sym[..], self.val_ty(sc)).unwrap_or_else(|| {
121                 bug!("symbol `{}` is already defined", sym);
122             });
123             llvm::LLVMSetInitializer(g, sc);
124             llvm::LLVMSetGlobalConstant(g, True);
125             llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
126
127             self.const_cstr_cache.borrow_mut().insert(s, g);
128             g
129         }
130     }
131
132     pub fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
133         unsafe {
134             assert_eq!(idx as c_uint as u64, idx);
135             let us = &[idx as c_uint];
136             let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
137
138             debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
139
140             r
141         }
142     }
143 }
144
145 impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
146     fn const_null(&self, t: &'ll Type) -> &'ll Value {
147         unsafe { llvm::LLVMConstNull(t) }
148     }
149
150     fn const_undef(&self, t: &'ll Type) -> &'ll Value {
151         unsafe { llvm::LLVMGetUndef(t) }
152     }
153
154     fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
155         unsafe { llvm::LLVMConstInt(t, i as u64, True) }
156     }
157
158     fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
159         unsafe { llvm::LLVMConstInt(t, i, False) }
160     }
161
162     fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
163         unsafe {
164             let words = [u as u64, (u >> 64) as u64];
165             llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
166         }
167     }
168
169     fn const_bool(&self, val: bool) -> &'ll Value {
170         self.const_uint(self.type_i1(), val as u64)
171     }
172
173     fn const_i32(&self, i: i32) -> &'ll Value {
174         self.const_int(self.type_i32(), i as i64)
175     }
176
177     fn const_u32(&self, i: u32) -> &'ll Value {
178         self.const_uint(self.type_i32(), i as u64)
179     }
180
181     fn const_u64(&self, i: u64) -> &'ll Value {
182         self.const_uint(self.type_i64(), i)
183     }
184
185     fn const_usize(&self, i: u64) -> &'ll Value {
186         let bit_size = self.data_layout().pointer_size.bits();
187         if bit_size < 64 {
188             // make sure it doesn't overflow
189             assert!(i < (1 << bit_size));
190         }
191
192         self.const_uint(self.isize_ty, i)
193     }
194
195     fn const_u8(&self, i: u8) -> &'ll Value {
196         self.const_uint(self.type_i8(), i as u64)
197     }
198
199     fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
200         unsafe { llvm::LLVMConstReal(t, val) }
201     }
202
203     fn const_str(&self, s: Symbol) -> (&'ll Value, &'ll Value) {
204         let len = s.as_str().len();
205         let cs = consts::ptrcast(
206             self.const_cstr(s, false),
207             self.type_ptr_to(self.layout_of(self.tcx.types.str_).llvm_type(self)),
208         );
209         (cs, self.const_usize(len as u64))
210     }
211
212     fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
213         struct_in_context(self.llcx, elts, packed)
214     }
215
216     fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
217         try_as_const_integral(v).map(|v| unsafe { llvm::LLVMConstIntGetZExtValue(v) })
218     }
219
220     fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
221         try_as_const_integral(v).and_then(|v| unsafe {
222             let (mut lo, mut hi) = (0u64, 0u64);
223             let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
224             success.then_some(hi_lo_to_u128(lo, hi))
225         })
226     }
227
228     fn scalar_to_backend(&self, cv: Scalar, layout: &abi::Scalar, llty: &'ll Type) -> &'ll Value {
229         let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() };
230         match cv {
231             Scalar::Raw { size: 0, .. } => {
232                 assert_eq!(0, layout.value.size(self).bytes());
233                 self.const_undef(self.type_ix(0))
234             }
235             Scalar::Raw { data, size } => {
236                 assert_eq!(size as u64, layout.value.size(self).bytes());
237                 let llval = self.const_uint_big(self.type_ix(bitsize), data);
238                 if layout.value == Pointer {
239                     unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
240                 } else {
241                     self.const_bitcast(llval, llty)
242                 }
243             }
244             Scalar::Ptr(ptr) => {
245                 let (base_addr, base_addr_space) = match self.tcx.global_alloc(ptr.alloc_id) {
246                     GlobalAlloc::Memory(alloc) => {
247                         let init = const_alloc_to_llvm(self, alloc);
248                         let value = match alloc.mutability {
249                             Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
250                             _ => self.static_addr_of(init, alloc.align, None),
251                         };
252                         if !self.sess().fewer_names() {
253                             llvm::set_value_name(value, format!("{:?}", ptr.alloc_id).as_bytes());
254                         }
255                         (value, AddressSpace::DATA)
256                     }
257                     GlobalAlloc::Function(fn_instance) => (
258                         self.get_fn_addr(fn_instance.polymorphize(self.tcx)),
259                         self.data_layout().instruction_address_space,
260                     ),
261                     GlobalAlloc::Static(def_id) => {
262                         assert!(self.tcx.is_static(def_id));
263                         assert!(!self.tcx.is_thread_local_static(def_id));
264                         (self.get_static(def_id), AddressSpace::DATA)
265                     }
266                 };
267                 let llval = unsafe {
268                     llvm::LLVMConstInBoundsGEP(
269                         self.const_bitcast(base_addr, self.type_i8p_ext(base_addr_space)),
270                         &self.const_usize(ptr.offset.bytes()),
271                         1,
272                     )
273                 };
274                 if layout.value != Pointer {
275                     unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
276                 } else {
277                     self.const_bitcast(llval, llty)
278                 }
279             }
280         }
281     }
282
283     fn from_const_alloc(
284         &self,
285         layout: TyAndLayout<'tcx>,
286         alloc: &Allocation,
287         offset: Size,
288     ) -> PlaceRef<'tcx, &'ll Value> {
289         assert_eq!(alloc.align, layout.align.abi);
290         let llty = self.type_ptr_to(layout.llvm_type(self));
291         let llval = if layout.size == Size::ZERO {
292             let llval = self.const_usize(alloc.align.bytes());
293             unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
294         } else {
295             let init = const_alloc_to_llvm(self, alloc);
296             let base_addr = self.static_addr_of(init, alloc.align, None);
297
298             let llval = unsafe {
299                 llvm::LLVMConstInBoundsGEP(
300                     self.const_bitcast(base_addr, self.type_i8p()),
301                     &self.const_usize(offset.bytes()),
302                     1,
303                 )
304             };
305             self.const_bitcast(llval, llty)
306         };
307         PlaceRef::new_sized(llval, layout)
308     }
309
310     fn const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
311         consts::ptrcast(val, ty)
312     }
313 }
314
315 pub fn val_ty(v: &Value) -> &Type {
316     unsafe { llvm::LLVMTypeOf(v) }
317 }
318
319 pub fn bytes_in_context(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
320     unsafe {
321         let ptr = bytes.as_ptr() as *const c_char;
322         llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True)
323     }
324 }
325
326 pub fn struct_in_context(llcx: &'a llvm::Context, elts: &[&'a Value], packed: bool) -> &'a Value {
327     unsafe {
328         llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), elts.len() as c_uint, packed as Bool)
329     }
330 }
331
332 #[inline]
333 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
334     ((hi as u128) << 64) | (lo as u128)
335 }
336
337 fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
338     unsafe { llvm::LLVMIsAConstantInt(v) }
339 }