rustc_codegen_llvm/
common.rs

1//! Code that is useful in various codegen modules.
2
3use libc::{c_char, c_uint};
4use rustc_abi as abi;
5use rustc_abi::Primitive::Pointer;
6use rustc_abi::{AddressSpace, HasDataLayout};
7use rustc_ast::Mutability;
8use rustc_codegen_ssa::common::TypeKind;
9use rustc_codegen_ssa::traits::*;
10use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher};
11use rustc_hir::def_id::DefId;
12use rustc_middle::bug;
13use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar};
14use rustc_middle::ty::TyCtxt;
15use rustc_session::cstore::DllImport;
16use tracing::debug;
17
18use crate::consts::const_alloc_to_llvm;
19pub(crate) use crate::context::CodegenCx;
20use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, Metadata, True};
21use crate::type_::Type;
22use crate::value::Value;
23
24/*
25* A note on nomenclature of linking: "extern", "foreign", and "upcall".
26*
27* An "extern" is an LLVM symbol we wind up emitting an undefined external
28* reference to. This means "we don't have the thing in this compilation unit,
29* please make sure you link it in at runtime". This could be a reference to
30* C code found in a C library, or rust code found in a rust crate.
31*
32* Most "externs" are implicitly declared (automatically) as a result of a
33* user declaring an extern _module_ dependency; this causes the rust driver
34* to locate an extern crate, scan its compilation metadata, and emit extern
35* declarations for any symbols used by the declaring crate.
36*
37* A "foreign" is an extern that references C (or other non-rust ABI) code.
38* There is no metadata to scan for extern references so in these cases either
39* a header-digester like bindgen, or manual function prototypes, have to
40* serve as declarators. So these are usually given explicitly as prototype
41* declarations, in rust code, with ABI attributes on them noting which ABI to
42* link via.
43*
44* An "upcall" is a foreign call generated by the compiler (not corresponding
45* to any user-written call in the code) into the runtime library, to perform
46* some helper task such as bringing a task to life, allocating memory, etc.
47*
48*/
49
50/// A structure representing an active landing pad for the duration of a basic
51/// block.
52///
53/// Each `Block` may contain an instance of this, indicating whether the block
54/// is part of a landing pad or not. This is used to make decision about whether
55/// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
56/// use `invoke`) and also about various function call metadata.
57///
58/// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
59/// just a bunch of `None` instances (not too interesting), but for MSVC
60/// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
61/// When inside of a landing pad, each function call in LLVM IR needs to be
62/// annotated with which landing pad it's a part of. This is accomplished via
63/// the `OperandBundleDef` value created for MSVC landing pads.
64pub(crate) struct Funclet<'ll> {
65    cleanuppad: &'ll Value,
66    operand: llvm::OperandBundleOwned<'ll>,
67}
68
69impl<'ll> Funclet<'ll> {
70    pub(crate) fn new(cleanuppad: &'ll Value) -> Self {
71        Funclet { cleanuppad, operand: llvm::OperandBundleOwned::new("funclet", &[cleanuppad]) }
72    }
73
74    pub(crate) fn cleanuppad(&self) -> &'ll Value {
75        self.cleanuppad
76    }
77
78    pub(crate) fn bundle(&self) -> &llvm::OperandBundle<'ll> {
79        &self.operand
80    }
81}
82
83impl<'ll> BackendTypes for CodegenCx<'ll, '_> {
84    type Value = &'ll Value;
85    type Metadata = &'ll Metadata;
86    // FIXME(eddyb) replace this with a `Function` "subclass" of `Value`.
87    type Function = &'ll Value;
88
89    type BasicBlock = &'ll BasicBlock;
90    type Type = &'ll Type;
91    type Funclet = Funclet<'ll>;
92
93    type DIScope = &'ll llvm::debuginfo::DIScope;
94    type DILocation = &'ll llvm::debuginfo::DILocation;
95    type DIVariable = &'ll llvm::debuginfo::DIVariable;
96}
97
98impl<'ll> CodegenCx<'ll, '_> {
99    pub(crate) fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
100        let len = u64::try_from(elts.len()).expect("LLVMConstArray2 elements len overflow");
101        unsafe { llvm::LLVMConstArray2(ty, elts.as_ptr(), len) }
102    }
103
104    pub(crate) fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
105        bytes_in_context(self.llcx, bytes)
106    }
107
108    pub(crate) fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
109        unsafe {
110            let idx = c_uint::try_from(idx).expect("LLVMGetAggregateElement index overflow");
111            let r = llvm::LLVMGetAggregateElement(v, idx).unwrap();
112
113            debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
114
115            r
116        }
117    }
118}
119
120impl<'ll, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> {
121    fn const_null(&self, t: &'ll Type) -> &'ll Value {
122        unsafe { llvm::LLVMConstNull(t) }
123    }
124
125    fn const_undef(&self, t: &'ll Type) -> &'ll Value {
126        unsafe { llvm::LLVMGetUndef(t) }
127    }
128
129    fn is_undef(&self, v: &'ll Value) -> bool {
130        unsafe { llvm::LLVMIsUndef(v) == True }
131    }
132
133    fn const_poison(&self, t: &'ll Type) -> &'ll Value {
134        unsafe { llvm::LLVMGetPoison(t) }
135    }
136
137    fn const_bool(&self, val: bool) -> &'ll Value {
138        self.const_uint(self.type_i1(), val as u64)
139    }
140
141    fn const_i8(&self, i: i8) -> &'ll Value {
142        self.const_int(self.type_i8(), i as i64)
143    }
144
145    fn const_i16(&self, i: i16) -> &'ll Value {
146        self.const_int(self.type_i16(), i as i64)
147    }
148
149    fn const_i32(&self, i: i32) -> &'ll Value {
150        self.const_int(self.type_i32(), i as i64)
151    }
152
153    fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
154        debug_assert!(
155            self.type_kind(t) == TypeKind::Integer,
156            "only allows integer types in const_int"
157        );
158        unsafe { llvm::LLVMConstInt(t, i as u64, True) }
159    }
160
161    fn const_u8(&self, i: u8) -> &'ll Value {
162        self.const_uint(self.type_i8(), i as u64)
163    }
164
165    fn const_u32(&self, i: u32) -> &'ll Value {
166        self.const_uint(self.type_i32(), i as u64)
167    }
168
169    fn const_u64(&self, i: u64) -> &'ll Value {
170        self.const_uint(self.type_i64(), i)
171    }
172
173    fn const_u128(&self, i: u128) -> &'ll Value {
174        self.const_uint_big(self.type_i128(), i)
175    }
176
177    fn const_usize(&self, i: u64) -> &'ll Value {
178        let bit_size = self.data_layout().pointer_size.bits();
179        if bit_size < 64 {
180            // make sure it doesn't overflow
181            assert!(i < (1 << bit_size));
182        }
183
184        self.const_uint(self.isize_ty, i)
185    }
186
187    fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
188        debug_assert!(
189            self.type_kind(t) == TypeKind::Integer,
190            "only allows integer types in const_uint"
191        );
192        unsafe { llvm::LLVMConstInt(t, i, False) }
193    }
194
195    fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
196        debug_assert!(
197            self.type_kind(t) == TypeKind::Integer,
198            "only allows integer types in const_uint_big"
199        );
200        unsafe {
201            let words = [u as u64, (u >> 64) as u64];
202            llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
203        }
204    }
205
206    fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
207        unsafe { llvm::LLVMConstReal(t, val) }
208    }
209
210    fn const_str(&self, s: &str) -> (&'ll Value, &'ll Value) {
211        let str_global = *self
212            .const_str_cache
213            .borrow_mut()
214            .raw_entry_mut()
215            .from_key(s)
216            .or_insert_with(|| {
217                let sc = self.const_bytes(s.as_bytes());
218                let sym = self.generate_local_symbol_name("str");
219                let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
220                    bug!("symbol `{}` is already defined", sym);
221                });
222                llvm::set_initializer(g, sc);
223                unsafe {
224                    llvm::LLVMSetGlobalConstant(g, True);
225                    llvm::LLVMSetUnnamedAddress(g, llvm::UnnamedAddr::Global);
226                }
227                llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
228                // Cast to default address space if globals are in a different addrspace
229                let g = self.const_pointercast(g, self.type_ptr());
230                (s.to_owned(), g)
231            })
232            .1;
233        let len = s.len();
234        (str_global, self.const_usize(len as u64))
235    }
236
237    fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
238        struct_in_context(self.llcx, elts, packed)
239    }
240
241    fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
242        let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
243        unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
244    }
245
246    fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
247        try_as_const_integral(v).and_then(|v| unsafe {
248            let mut i = 0u64;
249            let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
250            success.then_some(i)
251        })
252    }
253
254    fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
255        try_as_const_integral(v).and_then(|v| unsafe {
256            let (mut lo, mut hi) = (0u64, 0u64);
257            let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
258            success.then_some(hi_lo_to_u128(lo, hi))
259        })
260    }
261
262    fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value {
263        let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
264        match cv {
265            Scalar::Int(int) => {
266                let data = int.to_bits(layout.size(self));
267                let llval = self.const_uint_big(self.type_ix(bitsize), data);
268                if matches!(layout.primitive(), Pointer(_)) {
269                    unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
270                } else {
271                    self.const_bitcast(llval, llty)
272                }
273            }
274            Scalar::Ptr(ptr, _size) => {
275                let (prov, offset) = ptr.into_parts();
276                let (base_addr, base_addr_space) = match self.tcx.global_alloc(prov.alloc_id()) {
277                    GlobalAlloc::Memory(alloc) => {
278                        // For ZSTs directly codegen an aligned pointer.
279                        // This avoids generating a zero-sized constant value and actually needing a
280                        // real address at runtime.
281                        if alloc.inner().len() == 0 {
282                            assert_eq!(offset.bytes(), 0);
283                            let llval = self.const_usize(alloc.inner().align.bytes());
284                            return if matches!(layout.primitive(), Pointer(_)) {
285                                unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
286                            } else {
287                                self.const_bitcast(llval, llty)
288                            };
289                        } else {
290                            let init = const_alloc_to_llvm(self, alloc, /*static*/ false);
291                            let alloc = alloc.inner();
292                            let value = match alloc.mutability {
293                                Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
294                                _ => self.static_addr_of_impl(init, alloc.align, None),
295                            };
296                            if !self.sess().fewer_names() && llvm::get_value_name(value).is_empty()
297                            {
298                                let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
299                                    let mut hasher = StableHasher::new();
300                                    alloc.hash_stable(&mut hcx, &mut hasher);
301                                    hasher.finish::<Hash128>()
302                                });
303                                llvm::set_value_name(
304                                    value,
305                                    format!("alloc_{hash:032x}").as_bytes(),
306                                );
307                            }
308                            (value, AddressSpace::DATA)
309                        }
310                    }
311                    GlobalAlloc::Function { instance, .. } => {
312                        (self.get_fn_addr(instance), self.data_layout().instruction_address_space)
313                    }
314                    GlobalAlloc::VTable(ty, dyn_ty) => {
315                        let alloc = self
316                            .tcx
317                            .global_alloc(self.tcx.vtable_allocation((
318                                ty,
319                                dyn_ty.principal().map(|principal| {
320                                    self.tcx.instantiate_bound_regions_with_erased(principal)
321                                }),
322                            )))
323                            .unwrap_memory();
324                        let init = const_alloc_to_llvm(self, alloc, /*static*/ false);
325                        let value = self.static_addr_of_impl(init, alloc.inner().align, None);
326                        (value, AddressSpace::DATA)
327                    }
328                    GlobalAlloc::Static(def_id) => {
329                        assert!(self.tcx.is_static(def_id));
330                        assert!(!self.tcx.is_thread_local_static(def_id));
331                        (self.get_static(def_id), AddressSpace::DATA)
332                    }
333                };
334                let llval = unsafe {
335                    llvm::LLVMConstInBoundsGEP2(
336                        self.type_i8(),
337                        // Cast to the required address space if necessary
338                        self.const_pointercast(base_addr, self.type_ptr_ext(base_addr_space)),
339                        &self.const_usize(offset.bytes()),
340                        1,
341                    )
342                };
343                if !matches!(layout.primitive(), Pointer(_)) {
344                    unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
345                } else {
346                    self.const_bitcast(llval, llty)
347                }
348            }
349        }
350    }
351
352    fn const_data_from_alloc(&self, alloc: ConstAllocation<'tcx>) -> Self::Value {
353        const_alloc_to_llvm(self, alloc, /*static*/ false)
354    }
355
356    fn const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value {
357        unsafe {
358            llvm::LLVMConstInBoundsGEP2(
359                self.type_i8(),
360                base_addr,
361                &self.const_usize(offset.bytes()),
362                1,
363            )
364        }
365    }
366}
367
368/// Get the [LLVM type][Type] of a [`Value`].
369pub(crate) fn val_ty(v: &Value) -> &Type {
370    unsafe { llvm::LLVMTypeOf(v) }
371}
372
373pub(crate) fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
374    unsafe {
375        let ptr = bytes.as_ptr() as *const c_char;
376        llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), True)
377    }
378}
379
380fn struct_in_context<'ll>(
381    llcx: &'ll llvm::Context,
382    elts: &[&'ll Value],
383    packed: bool,
384) -> &'ll Value {
385    let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
386    unsafe { llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), len, packed as Bool) }
387}
388
389#[inline]
390fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
391    ((hi as u128) << 64) | (lo as u128)
392}
393
394fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
395    unsafe { llvm::LLVMIsAConstantInt(v) }
396}
397
398pub(crate) fn get_dllimport<'tcx>(
399    tcx: TyCtxt<'tcx>,
400    id: DefId,
401    name: &str,
402) -> Option<&'tcx DllImport> {
403    tcx.native_library(id)
404        .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
405}
406
407/// Extension trait for explicit casts to `*const c_char`.
408pub(crate) trait AsCCharPtr {
409    /// Equivalent to `self.as_ptr().cast()`, but only casts to `*const c_char`.
410    fn as_c_char_ptr(&self) -> *const c_char;
411}
412
413impl AsCCharPtr for str {
414    fn as_c_char_ptr(&self) -> *const c_char {
415        self.as_ptr().cast()
416    }
417}
418
419impl AsCCharPtr for [u8] {
420    fn as_c_char_ptr(&self) -> *const c_char {
421        self.as_ptr().cast()
422    }
423}