rustc_codegen_llvm/
common.rs

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