]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/common.rs
fix `emit_inference_failure_err` ICE
[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::{ConstAllocation, 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     pub fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
110         unsafe {
111             assert_eq!(idx as c_uint as u64, idx);
112             let us = &[idx as c_uint];
113             let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
114
115             debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
116
117             r
118         }
119     }
120 }
121
122 impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
123     fn const_null(&self, t: &'ll Type) -> &'ll Value {
124         unsafe { llvm::LLVMConstNull(t) }
125     }
126
127     fn const_undef(&self, t: &'ll Type) -> &'ll Value {
128         unsafe { llvm::LLVMGetUndef(t) }
129     }
130
131     fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
132         unsafe { llvm::LLVMConstInt(t, i as u64, True) }
133     }
134
135     fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
136         unsafe { llvm::LLVMConstInt(t, i, False) }
137     }
138
139     fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
140         unsafe {
141             let words = [u as u64, (u >> 64) as u64];
142             llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
143         }
144     }
145
146     fn const_bool(&self, val: bool) -> &'ll Value {
147         self.const_uint(self.type_i1(), val as u64)
148     }
149
150     fn const_i16(&self, i: i16) -> &'ll Value {
151         self.const_int(self.type_i16(), i as i64)
152     }
153
154     fn const_i32(&self, i: i32) -> &'ll Value {
155         self.const_int(self.type_i32(), i as i64)
156     }
157
158     fn const_u32(&self, i: u32) -> &'ll Value {
159         self.const_uint(self.type_i32(), i as u64)
160     }
161
162     fn const_u64(&self, i: u64) -> &'ll Value {
163         self.const_uint(self.type_i64(), i)
164     }
165
166     fn const_usize(&self, i: u64) -> &'ll Value {
167         let bit_size = self.data_layout().pointer_size.bits();
168         if bit_size < 64 {
169             // make sure it doesn't overflow
170             assert!(i < (1 << bit_size));
171         }
172
173         self.const_uint(self.isize_ty, i)
174     }
175
176     fn const_u8(&self, i: u8) -> &'ll Value {
177         self.const_uint(self.type_i8(), i as u64)
178     }
179
180     fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
181         unsafe { llvm::LLVMConstReal(t, val) }
182     }
183
184     fn const_str(&self, s: Symbol) -> (&'ll Value, &'ll Value) {
185         let s_str = s.as_str();
186         let str_global = *self.const_str_cache.borrow_mut().entry(s).or_insert_with(|| {
187             let sc = self.const_bytes(s_str.as_bytes());
188             let sym = self.generate_local_symbol_name("str");
189             let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
190                 bug!("symbol `{}` is already defined", sym);
191             });
192             unsafe {
193                 llvm::LLVMSetInitializer(g, sc);
194                 llvm::LLVMSetGlobalConstant(g, True);
195                 llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
196             }
197             g
198         });
199         let len = s_str.len();
200         let cs = consts::ptrcast(
201             str_global,
202             self.type_ptr_to(self.layout_of(self.tcx.types.str_).llvm_type(self)),
203         );
204         (cs, self.const_usize(len as u64))
205     }
206
207     fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
208         struct_in_context(self.llcx, elts, packed)
209     }
210
211     fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
212         try_as_const_integral(v).map(|v| unsafe { llvm::LLVMConstIntGetZExtValue(v) })
213     }
214
215     fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
216         try_as_const_integral(v).and_then(|v| unsafe {
217             let (mut lo, mut hi) = (0u64, 0u64);
218             let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
219             success.then_some(hi_lo_to_u128(lo, hi))
220         })
221     }
222
223     fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value {
224         let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
225         match cv {
226             Scalar::Int(ScalarInt::ZST) => {
227                 assert_eq!(0, layout.size(self).bytes());
228                 self.const_undef(self.type_ix(0))
229             }
230             Scalar::Int(int) => {
231                 let data = int.assert_bits(layout.size(self));
232                 let llval = self.const_uint_big(self.type_ix(bitsize), data);
233                 if layout.primitive() == Pointer {
234                     unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
235                 } else {
236                     self.const_bitcast(llval, llty)
237                 }
238             }
239             Scalar::Ptr(ptr, _size) => {
240                 let (alloc_id, offset) = ptr.into_parts();
241                 let (base_addr, base_addr_space) = match self.tcx.global_alloc(alloc_id) {
242                     GlobalAlloc::Memory(alloc) => {
243                         let init = const_alloc_to_llvm(self, alloc);
244                         let alloc = alloc.inner();
245                         let value = match alloc.mutability {
246                             Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
247                             _ => self.static_addr_of(init, alloc.align, None),
248                         };
249                         if !self.sess().fewer_names() {
250                             llvm::set_value_name(value, format!("{:?}", alloc_id).as_bytes());
251                         }
252                         (value, AddressSpace::DATA)
253                     }
254                     GlobalAlloc::Function(fn_instance) => (
255                         self.get_fn_addr(fn_instance.polymorphize(self.tcx)),
256                         self.data_layout().instruction_address_space,
257                     ),
258                     GlobalAlloc::Static(def_id) => {
259                         assert!(self.tcx.is_static(def_id));
260                         assert!(!self.tcx.is_thread_local_static(def_id));
261                         (self.get_static(def_id), AddressSpace::DATA)
262                     }
263                 };
264                 let llval = unsafe {
265                     llvm::LLVMRustConstInBoundsGEP2(
266                         self.type_i8(),
267                         self.const_bitcast(base_addr, self.type_i8p_ext(base_addr_space)),
268                         &self.const_usize(offset.bytes()),
269                         1,
270                     )
271                 };
272                 if layout.primitive() != Pointer {
273                     unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
274                 } else {
275                     self.const_bitcast(llval, llty)
276                 }
277             }
278         }
279     }
280
281     fn const_data_from_alloc(&self, alloc: ConstAllocation<'tcx>) -> Self::Value {
282         const_alloc_to_llvm(self, alloc)
283     }
284
285     fn from_const_alloc(
286         &self,
287         layout: TyAndLayout<'tcx>,
288         alloc: ConstAllocation<'tcx>,
289         offset: Size,
290     ) -> PlaceRef<'tcx, &'ll Value> {
291         let alloc_align = alloc.inner().align;
292         assert_eq!(alloc_align, layout.align.abi);
293         let llty = self.type_ptr_to(layout.llvm_type(self));
294         let llval = if layout.size == Size::ZERO {
295             let llval = self.const_usize(alloc_align.bytes());
296             unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
297         } else {
298             let init = const_alloc_to_llvm(self, alloc);
299             let base_addr = self.static_addr_of(init, alloc_align, None);
300
301             let llval = unsafe {
302                 llvm::LLVMRustConstInBoundsGEP2(
303                     self.type_i8(),
304                     self.const_bitcast(base_addr, self.type_i8p()),
305                     &self.const_usize(offset.bytes()),
306                     1,
307                 )
308             };
309             self.const_bitcast(llval, llty)
310         };
311         PlaceRef::new_sized(llval, layout)
312     }
313
314     fn const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
315         consts::ptrcast(val, ty)
316     }
317 }
318
319 /// Get the [LLVM type][Type] of a [`Value`].
320 pub fn val_ty(v: &Value) -> &Type {
321     unsafe { llvm::LLVMTypeOf(v) }
322 }
323
324 pub fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
325     unsafe {
326         let ptr = bytes.as_ptr() as *const c_char;
327         llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True)
328     }
329 }
330
331 pub fn struct_in_context<'ll>(
332     llcx: &'ll llvm::Context,
333     elts: &[&'ll Value],
334     packed: bool,
335 ) -> &'ll Value {
336     unsafe {
337         llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), elts.len() as c_uint, packed as Bool)
338     }
339 }
340
341 #[inline]
342 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
343     ((hi as u128) << 64) | (lo as u128)
344 }
345
346 fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
347     unsafe { llvm::LLVMIsAConstantInt(v) }
348 }