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