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, ConstantInt, FALSE, Metadata, TRUE, ToLlvmBool};
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 null_terminate_const_bytes(&self, bytes: &[u8]) -> &'ll Value {
112        null_terminate_bytes_in_context(self.llcx(), bytes)
113    }
114
115    pub(crate) fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
116        unsafe {
117            let idx = c_uint::try_from(idx).expect("LLVMGetAggregateElement index overflow");
118            let r = llvm::LLVMGetAggregateElement(v, idx).unwrap();
119
120            debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
121
122            r
123        }
124    }
125
126    pub(crate) fn const_null(&self, t: &'ll Type) -> &'ll Value {
127        unsafe { llvm::LLVMConstNull(t) }
128    }
129}
130
131impl<'ll, 'tcx> ConstCodegenMethods for CodegenCx<'ll, 'tcx> {
132    fn const_null(&self, t: &'ll Type) -> &'ll Value {
133        unsafe { llvm::LLVMConstNull(t) }
134    }
135
136    fn const_undef(&self, t: &'ll Type) -> &'ll Value {
137        unsafe { llvm::LLVMGetUndef(t) }
138    }
139
140    fn const_poison(&self, t: &'ll Type) -> &'ll Value {
141        unsafe { llvm::LLVMGetPoison(t) }
142    }
143
144    fn const_bool(&self, val: bool) -> &'ll Value {
145        self.const_uint(self.type_i1(), val as u64)
146    }
147
148    fn const_i8(&self, i: i8) -> &'ll Value {
149        self.const_int(self.type_i8(), i as i64)
150    }
151
152    fn const_i16(&self, i: i16) -> &'ll Value {
153        self.const_int(self.type_i16(), i as i64)
154    }
155
156    fn const_i32(&self, i: i32) -> &'ll Value {
157        self.const_int(self.type_i32(), i as i64)
158    }
159
160    fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
161        debug_assert!(
162            self.type_kind(t) == TypeKind::Integer,
163            "only allows integer types in const_int"
164        );
165        unsafe { llvm::LLVMConstInt(t, i as u64, TRUE) }
166    }
167
168    fn const_u8(&self, i: u8) -> &'ll Value {
169        self.const_uint(self.type_i8(), i as u64)
170    }
171
172    fn const_u32(&self, i: u32) -> &'ll Value {
173        self.const_uint(self.type_i32(), i as u64)
174    }
175
176    fn const_u64(&self, i: u64) -> &'ll Value {
177        self.const_uint(self.type_i64(), i)
178    }
179
180    fn const_u128(&self, i: u128) -> &'ll Value {
181        self.const_uint_big(self.type_i128(), i)
182    }
183
184    fn const_usize(&self, i: u64) -> &'ll Value {
185        let bit_size = self.data_layout().pointer_size().bits();
186        if bit_size < 64 {
187            // make sure it doesn't overflow
188            assert!(i < (1 << bit_size));
189        }
190
191        self.const_uint(self.isize_ty, i)
192    }
193
194    fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
195        debug_assert!(
196            self.type_kind(t) == TypeKind::Integer,
197            "only allows integer types in const_uint"
198        );
199        unsafe { llvm::LLVMConstInt(t, i, FALSE) }
200    }
201
202    fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
203        debug_assert!(
204            self.type_kind(t) == TypeKind::Integer,
205            "only allows integer types in const_uint_big"
206        );
207        unsafe {
208            let words = [u as u64, (u >> 64) as u64];
209            llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
210        }
211    }
212
213    fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
214        unsafe { llvm::LLVMConstReal(t, val) }
215    }
216
217    fn const_str(&self, s: &str) -> (&'ll Value, &'ll Value) {
218        let mut const_str_cache = self.const_str_cache.borrow_mut();
219        let str_global = const_str_cache.get(s).copied().unwrap_or_else(|| {
220            let sc = self.const_bytes(s.as_bytes());
221            let sym = self.generate_local_symbol_name("str");
222            let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
223                bug!("symbol `{}` is already defined", sym);
224            });
225            llvm::set_initializer(g, sc);
226
227            llvm::set_global_constant(g, true);
228            llvm::set_unnamed_address(g, llvm::UnnamedAddr::Global);
229
230            llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
231            // Cast to default address space if globals are in a different addrspace
232            let g = self.const_pointercast(g, self.type_ptr());
233            const_str_cache.insert(s.to_owned(), g);
234            g
235        });
236        let len = s.len();
237        (str_global, self.const_usize(len as u64))
238    }
239
240    fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
241        struct_in_context(self.llcx, elts, packed)
242    }
243
244    fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
245        let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
246        unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
247    }
248
249    fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
250        try_as_const_integral(v).and_then(|v| unsafe {
251            let mut i = 0u64;
252            let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
253            success.then_some(i)
254        })
255    }
256
257    fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
258        try_as_const_integral(v).and_then(|v| unsafe {
259            let (mut lo, mut hi) = (0u64, 0u64);
260            let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
261            success.then_some(hi_lo_to_u128(lo, hi))
262        })
263    }
264
265    fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value {
266        let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
267        match cv {
268            Scalar::Int(int) => {
269                let data = int.to_bits(layout.size(self));
270                let llval = self.const_uint_big(self.type_ix(bitsize), data);
271                if matches!(layout.primitive(), Pointer(_)) {
272                    unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
273                } else {
274                    self.const_bitcast(llval, llty)
275                }
276            }
277            Scalar::Ptr(ptr, _size) => {
278                let (prov, offset) = ptr.prov_and_relative_offset();
279                let global_alloc = self.tcx.global_alloc(prov.alloc_id());
280                let base_addr = match global_alloc {
281                    GlobalAlloc::Memory(alloc) => {
282                        // For ZSTs directly codegen an aligned pointer.
283                        // This avoids generating a zero-sized constant value and actually needing a
284                        // real address at runtime.
285                        if alloc.inner().len() == 0 {
286                            assert_eq!(offset.bytes(), 0);
287                            let llval = self.const_usize(alloc.inner().align.bytes());
288                            return if matches!(layout.primitive(), Pointer(_)) {
289                                unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
290                            } else {
291                                self.const_bitcast(llval, llty)
292                            };
293                        } else {
294                            let init =
295                                const_alloc_to_llvm(self, alloc.inner(), /*static*/ false);
296                            let alloc = alloc.inner();
297                            let value = match alloc.mutability {
298                                Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
299                                _ => self.static_addr_of_impl(init, alloc.align, None),
300                            };
301                            if !self.sess().fewer_names() && llvm::get_value_name(value).is_empty()
302                            {
303                                let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
304                                    let mut hasher = StableHasher::new();
305                                    alloc.hash_stable(&mut hcx, &mut hasher);
306                                    hasher.finish::<Hash128>()
307                                });
308                                llvm::set_value_name(
309                                    value,
310                                    format!("alloc_{hash:032x}").as_bytes(),
311                                );
312                            }
313                            value
314                        }
315                    }
316                    GlobalAlloc::Function { instance, .. } => self.get_fn_addr(instance),
317                    GlobalAlloc::VTable(ty, dyn_ty) => {
318                        let alloc = self
319                            .tcx
320                            .global_alloc(self.tcx.vtable_allocation((
321                                ty,
322                                dyn_ty.principal().map(|principal| {
323                                    self.tcx.instantiate_bound_regions_with_erased(principal)
324                                }),
325                            )))
326                            .unwrap_memory();
327                        let init = const_alloc_to_llvm(self, alloc.inner(), /*static*/ false);
328                        self.static_addr_of_impl(init, alloc.inner().align, None)
329                    }
330                    GlobalAlloc::Static(def_id) => {
331                        assert!(self.tcx.is_static(def_id));
332                        assert!(!self.tcx.is_thread_local_static(def_id));
333                        self.get_static(def_id)
334                    }
335                    GlobalAlloc::TypeId { .. } => {
336                        // Drop the provenance, the offset contains the bytes of the hash
337                        let llval = self.const_usize(offset.bytes());
338                        return unsafe { llvm::LLVMConstIntToPtr(llval, llty) };
339                    }
340                };
341                let base_addr_space = global_alloc.address_space(self);
342                let llval = unsafe {
343                    llvm::LLVMConstInBoundsGEP2(
344                        self.type_i8(),
345                        // Cast to the required address space if necessary
346                        self.const_pointercast(base_addr, self.type_ptr_ext(base_addr_space)),
347                        &self.const_usize(offset.bytes()),
348                        1,
349                    )
350                };
351                if !matches!(layout.primitive(), Pointer(_)) {
352                    unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
353                } else {
354                    self.const_bitcast(llval, llty)
355                }
356            }
357        }
358    }
359
360    fn const_data_from_alloc(&self, alloc: ConstAllocation<'_>) -> Self::Value {
361        const_alloc_to_llvm(self, alloc.inner(), /*static*/ false)
362    }
363
364    fn const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value {
365        unsafe {
366            llvm::LLVMConstInBoundsGEP2(
367                self.type_i8(),
368                base_addr,
369                &self.const_usize(offset.bytes()),
370                1,
371            )
372        }
373    }
374}
375
376/// Get the [LLVM type][Type] of a [`Value`].
377pub(crate) fn val_ty(v: &Value) -> &Type {
378    unsafe { llvm::LLVMTypeOf(v) }
379}
380
381pub(crate) fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
382    unsafe {
383        let ptr = bytes.as_ptr() as *const c_char;
384        llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), TRUE)
385    }
386}
387
388pub(crate) fn null_terminate_bytes_in_context<'ll>(
389    llcx: &'ll llvm::Context,
390    bytes: &[u8],
391) -> &'ll Value {
392    unsafe {
393        let ptr = bytes.as_ptr() as *const c_char;
394        llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), FALSE)
395    }
396}
397
398pub(crate) fn named_struct<'ll>(ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
399    let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
400    unsafe { llvm::LLVMConstNamedStruct(ty, elts.as_ptr(), len) }
401}
402
403fn struct_in_context<'ll>(
404    llcx: &'ll llvm::Context,
405    elts: &[&'ll Value],
406    packed: bool,
407) -> &'ll Value {
408    let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
409    unsafe { llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), len, packed.to_llvm_bool()) }
410}
411
412#[inline]
413fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
414    ((hi as u128) << 64) | (lo as u128)
415}
416
417fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
418    unsafe { llvm::LLVMIsAConstantInt(v) }
419}
420
421pub(crate) fn get_dllimport<'tcx>(
422    tcx: TyCtxt<'tcx>,
423    id: DefId,
424    name: &str,
425) -> Option<&'tcx DllImport> {
426    tcx.native_library(id)
427        .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
428}
429
430/// Extension trait for explicit casts to `*const c_char`.
431pub(crate) trait AsCCharPtr {
432    /// Equivalent to `self.as_ptr().cast()`, but only casts to `*const c_char`.
433    fn as_c_char_ptr(&self) -> *const c_char;
434}
435
436impl AsCCharPtr for str {
437    fn as_c_char_ptr(&self) -> *const c_char {
438        self.as_ptr().cast()
439    }
440}
441
442impl AsCCharPtr for [u8] {
443    fn as_c_char_ptr(&self) -> *const c_char {
444        self.as_ptr().cast()
445    }
446}