• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::traits::*;
12 use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher};
13 use rustc_hir::def_id::DefId;
14 use rustc_middle::bug;
15 use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar};
16 use rustc_middle::ty::layout::LayoutOf;
17 use rustc_middle::ty::TyCtxt;
18 use rustc_session::cstore::{DllCallingConvention, DllImport, PeImportNameType};
19 use rustc_target::abi::{self, AddressSpace, HasDataLayout, Pointer};
20 use rustc_target::spec::Target;
21 
22 use libc::{c_char, c_uint};
23 use std::fmt::Write;
24 
25 /*
26 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
27 *
28 * An "extern" is an LLVM symbol we wind up emitting an undefined external
29 * reference to. This means "we don't have the thing in this compilation unit,
30 * please make sure you link it in at runtime". This could be a reference to
31 * C code found in a C library, or rust code found in a rust crate.
32 *
33 * Most "externs" are implicitly declared (automatically) as a result of a
34 * user declaring an extern _module_ dependency; this causes the rust driver
35 * to locate an extern crate, scan its compilation metadata, and emit extern
36 * declarations for any symbols used by the declaring crate.
37 *
38 * A "foreign" is an extern that references C (or other non-rust ABI) code.
39 * There is no metadata to scan for extern references so in these cases either
40 * a header-digester like bindgen, or manual function prototypes, have to
41 * serve as declarators. So these are usually given explicitly as prototype
42 * declarations, in rust code, with ABI attributes on them noting which ABI to
43 * link via.
44 *
45 * An "upcall" is a foreign call generated by the compiler (not corresponding
46 * to any user-written call in the code) into the runtime library, to perform
47 * some helper task such as bringing a task to life, allocating memory, etc.
48 *
49 */
50 
51 /// A structure representing an active landing pad for the duration of a basic
52 /// block.
53 ///
54 /// Each `Block` may contain an instance of this, indicating whether the block
55 /// is part of a landing pad or not. This is used to make decision about whether
56 /// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
57 /// use `invoke`) and also about various function call metadata.
58 ///
59 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
60 /// just a bunch of `None` instances (not too interesting), but for MSVC
61 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
62 /// When inside of a landing pad, each function call in LLVM IR needs to be
63 /// annotated with which landing pad it's a part of. This is accomplished via
64 /// the `OperandBundleDef` value created for MSVC landing pads.
65 pub struct Funclet<'ll> {
66     cleanuppad: &'ll Value,
67     operand: OperandBundleDef<'ll>,
68 }
69 
70 impl<'ll> Funclet<'ll> {
new(cleanuppad: &'ll Value) -> Self71     pub fn new(cleanuppad: &'ll Value) -> Self {
72         Funclet { cleanuppad, operand: OperandBundleDef::new("funclet", &[cleanuppad]) }
73     }
74 
cleanuppad(&self) -> &'ll Value75     pub fn cleanuppad(&self) -> &'ll Value {
76         self.cleanuppad
77     }
78 
bundle(&self) -> &OperandBundleDef<'ll>79     pub fn bundle(&self) -> &OperandBundleDef<'ll> {
80         &self.operand
81     }
82 }
83 
84 impl<'ll> BackendTypes for CodegenCx<'ll, '_> {
85     type Value = &'ll Value;
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 
98 impl<'ll> CodegenCx<'ll, '_> {
const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value99     pub fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
100         unsafe { llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint) }
101     }
102 
const_vector(&self, elts: &[&'ll Value]) -> &'ll Value103     pub fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
104         unsafe { llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint) }
105     }
106 
const_bytes(&self, bytes: &[u8]) -> &'ll Value107     pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
108         bytes_in_context(self.llcx, bytes)
109     }
110 
const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value111     pub fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
112         unsafe {
113             assert_eq!(idx as c_uint as u64, idx);
114             let r = llvm::LLVMGetAggregateElement(v, idx as c_uint).unwrap();
115 
116             debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
117 
118             r
119         }
120     }
121 }
122 
123 impl<'ll, 'tcx> ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
const_null(&self, t: &'ll Type) -> &'ll Value124     fn const_null(&self, t: &'ll Type) -> &'ll Value {
125         unsafe { llvm::LLVMConstNull(t) }
126     }
127 
const_undef(&self, t: &'ll Type) -> &'ll Value128     fn const_undef(&self, t: &'ll Type) -> &'ll Value {
129         unsafe { llvm::LLVMGetUndef(t) }
130     }
131 
const_poison(&self, t: &'ll Type) -> &'ll Value132     fn const_poison(&self, t: &'ll Type) -> &'ll Value {
133         unsafe { llvm::LLVMGetPoison(t) }
134     }
135 
const_int(&self, t: &'ll Type, i: i64) -> &'ll Value136     fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
137         unsafe { llvm::LLVMConstInt(t, i as u64, True) }
138     }
139 
const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value140     fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
141         unsafe { llvm::LLVMConstInt(t, i, False) }
142     }
143 
const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value144     fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
145         unsafe {
146             let words = [u as u64, (u >> 64) as u64];
147             llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
148         }
149     }
150 
const_bool(&self, val: bool) -> &'ll Value151     fn const_bool(&self, val: bool) -> &'ll Value {
152         self.const_uint(self.type_i1(), val as u64)
153     }
154 
const_i16(&self, i: i16) -> &'ll Value155     fn const_i16(&self, i: i16) -> &'ll Value {
156         self.const_int(self.type_i16(), i as i64)
157     }
158 
const_i32(&self, i: i32) -> &'ll Value159     fn const_i32(&self, i: i32) -> &'ll Value {
160         self.const_int(self.type_i32(), i as i64)
161     }
162 
const_u32(&self, i: u32) -> &'ll Value163     fn const_u32(&self, i: u32) -> &'ll Value {
164         self.const_uint(self.type_i32(), i as u64)
165     }
166 
const_u64(&self, i: u64) -> &'ll Value167     fn const_u64(&self, i: u64) -> &'ll Value {
168         self.const_uint(self.type_i64(), i)
169     }
170 
const_u128(&self, i: u128) -> &'ll Value171     fn const_u128(&self, i: u128) -> &'ll Value {
172         self.const_uint_big(self.type_i128(), i)
173     }
174 
const_usize(&self, i: u64) -> &'ll Value175     fn const_usize(&self, i: u64) -> &'ll Value {
176         let bit_size = self.data_layout().pointer_size.bits();
177         if bit_size < 64 {
178             // make sure it doesn't overflow
179             assert!(i < (1 << bit_size));
180         }
181 
182         self.const_uint(self.isize_ty, i)
183     }
184 
const_u8(&self, i: u8) -> &'ll Value185     fn const_u8(&self, i: u8) -> &'ll Value {
186         self.const_uint(self.type_i8(), i as u64)
187     }
188 
const_real(&self, t: &'ll Type, val: f64) -> &'ll Value189     fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
190         unsafe { llvm::LLVMConstReal(t, val) }
191     }
192 
const_str(&self, s: &str) -> (&'ll Value, &'ll Value)193     fn const_str(&self, s: &str) -> (&'ll Value, &'ll Value) {
194         let str_global = *self
195             .const_str_cache
196             .borrow_mut()
197             .raw_entry_mut()
198             .from_key(s)
199             .or_insert_with(|| {
200                 let sc = self.const_bytes(s.as_bytes());
201                 let sym = self.generate_local_symbol_name("str");
202                 let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
203                     bug!("symbol `{}` is already defined", sym);
204                 });
205                 unsafe {
206                     llvm::LLVMSetInitializer(g, sc);
207                     llvm::LLVMSetGlobalConstant(g, True);
208                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
209                 }
210                 (s.to_owned(), g)
211             })
212             .1;
213         let len = s.len();
214         let cs = consts::ptrcast(
215             str_global,
216             self.type_ptr_to(self.layout_of(self.tcx.types.str_).llvm_type(self)),
217         );
218         (cs, self.const_usize(len as u64))
219     }
220 
const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value221     fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
222         struct_in_context(self.llcx, elts, packed)
223     }
224 
const_to_opt_uint(&self, v: &'ll Value) -> Option<u64>225     fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
226         try_as_const_integral(v).and_then(|v| unsafe {
227             let mut i = 0u64;
228             let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
229             success.then_some(i)
230         })
231     }
232 
const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128>233     fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
234         try_as_const_integral(v).and_then(|v| unsafe {
235             let (mut lo, mut hi) = (0u64, 0u64);
236             let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
237             success.then_some(hi_lo_to_u128(lo, hi))
238         })
239     }
240 
scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value241     fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value {
242         let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
243         match cv {
244             Scalar::Int(int) => {
245                 let data = int.assert_bits(layout.size(self));
246                 let llval = self.const_uint_big(self.type_ix(bitsize), data);
247                 if matches!(layout.primitive(), Pointer(_)) {
248                     unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
249                 } else {
250                     self.const_bitcast(llval, llty)
251                 }
252             }
253             Scalar::Ptr(ptr, _size) => {
254                 let (alloc_id, offset) = ptr.into_parts();
255                 let (base_addr, base_addr_space) = match self.tcx.global_alloc(alloc_id) {
256                     GlobalAlloc::Memory(alloc) => {
257                         let init = const_alloc_to_llvm(self, alloc);
258                         let alloc = alloc.inner();
259                         let value = match alloc.mutability {
260                             Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
261                             _ => self.static_addr_of(init, alloc.align, None),
262                         };
263                         if !self.sess().fewer_names() && llvm::get_value_name(value).is_empty() {
264                             let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
265                                 let mut hasher = StableHasher::new();
266                                 alloc.hash_stable(&mut hcx, &mut hasher);
267                                 hasher.finish::<Hash128>()
268                             });
269                             llvm::set_value_name(value, format!("alloc_{hash:032x}").as_bytes());
270                         }
271                         (value, AddressSpace::DATA)
272                     }
273                     GlobalAlloc::Function(fn_instance) => (
274                         self.get_fn_addr(fn_instance.polymorphize(self.tcx)),
275                         self.data_layout().instruction_address_space,
276                     ),
277                     GlobalAlloc::VTable(ty, trait_ref) => {
278                         let alloc = self
279                             .tcx
280                             .global_alloc(self.tcx.vtable_allocation((ty, trait_ref)))
281                             .unwrap_memory();
282                         let init = const_alloc_to_llvm(self, alloc);
283                         let value = self.static_addr_of(init, alloc.inner().align, None);
284                         (value, AddressSpace::DATA)
285                     }
286                     GlobalAlloc::Static(def_id) => {
287                         assert!(self.tcx.is_static(def_id));
288                         assert!(!self.tcx.is_thread_local_static(def_id));
289                         (self.get_static(def_id), AddressSpace::DATA)
290                     }
291                 };
292                 let llval = unsafe {
293                     llvm::LLVMRustConstInBoundsGEP2(
294                         self.type_i8(),
295                         self.const_bitcast(base_addr, self.type_i8p_ext(base_addr_space)),
296                         &self.const_usize(offset.bytes()),
297                         1,
298                     )
299                 };
300                 if !matches!(layout.primitive(), Pointer(_)) {
301                     unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
302                 } else {
303                     self.const_bitcast(llval, llty)
304                 }
305             }
306         }
307     }
308 
const_data_from_alloc(&self, alloc: ConstAllocation<'tcx>) -> Self::Value309     fn const_data_from_alloc(&self, alloc: ConstAllocation<'tcx>) -> Self::Value {
310         const_alloc_to_llvm(self, alloc)
311     }
312 
const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value313     fn const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
314         consts::ptrcast(val, ty)
315     }
316 
const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value317     fn const_bitcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
318         self.const_bitcast(val, ty)
319     }
320 
const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value321     fn const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value {
322         unsafe {
323             llvm::LLVMRustConstInBoundsGEP2(
324                 self.type_i8(),
325                 self.const_bitcast(base_addr, self.type_i8p()),
326                 &self.const_usize(offset.bytes()),
327                 1,
328             )
329         }
330     }
331 }
332 
333 /// Get the [LLVM type][Type] of a [`Value`].
val_ty(v: &Value) -> &Type334 pub fn val_ty(v: &Value) -> &Type {
335     unsafe { llvm::LLVMTypeOf(v) }
336 }
337 
bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value338 pub fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
339     unsafe {
340         let ptr = bytes.as_ptr() as *const c_char;
341         llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True)
342     }
343 }
344 
struct_in_context<'ll>( llcx: &'ll llvm::Context, elts: &[&'ll Value], packed: bool, ) -> &'ll Value345 pub fn struct_in_context<'ll>(
346     llcx: &'ll llvm::Context,
347     elts: &[&'ll Value],
348     packed: bool,
349 ) -> &'ll Value {
350     unsafe {
351         llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), elts.len() as c_uint, packed as Bool)
352     }
353 }
354 
355 #[inline]
hi_lo_to_u128(lo: u64, hi: u64) -> u128356 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
357     ((hi as u128) << 64) | (lo as u128)
358 }
359 
try_as_const_integral(v: &Value) -> Option<&ConstantInt>360 fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
361     unsafe { llvm::LLVMIsAConstantInt(v) }
362 }
363 
get_dllimport<'tcx>( tcx: TyCtxt<'tcx>, id: DefId, name: &str, ) -> Option<&'tcx DllImport>364 pub(crate) fn get_dllimport<'tcx>(
365     tcx: TyCtxt<'tcx>,
366     id: DefId,
367     name: &str,
368 ) -> Option<&'tcx DllImport> {
369     tcx.native_library(id)
370         .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
371 }
372 
is_mingw_gnu_toolchain(target: &Target) -> bool373 pub(crate) fn is_mingw_gnu_toolchain(target: &Target) -> bool {
374     target.vendor == "pc" && target.os == "windows" && target.env == "gnu" && target.abi.is_empty()
375 }
376 
i686_decorated_name( dll_import: &DllImport, mingw: bool, disable_name_mangling: bool, ) -> String377 pub(crate) fn i686_decorated_name(
378     dll_import: &DllImport,
379     mingw: bool,
380     disable_name_mangling: bool,
381 ) -> String {
382     let name = dll_import.name.as_str();
383 
384     let (add_prefix, add_suffix) = match dll_import.import_name_type {
385         Some(PeImportNameType::NoPrefix) => (false, true),
386         Some(PeImportNameType::Undecorated) => (false, false),
387         _ => (true, true),
388     };
389 
390     // Worst case: +1 for disable name mangling, +1 for prefix, +4 for suffix (@@__).
391     let mut decorated_name = String::with_capacity(name.len() + 6);
392 
393     if disable_name_mangling {
394         // LLVM uses a binary 1 ('\x01') prefix to a name to indicate that mangling needs to be disabled.
395         decorated_name.push('\x01');
396     }
397 
398     let prefix = if add_prefix && dll_import.is_fn {
399         match dll_import.calling_convention {
400             DllCallingConvention::C | DllCallingConvention::Vectorcall(_) => None,
401             DllCallingConvention::Stdcall(_) => (!mingw
402                 || dll_import.import_name_type == Some(PeImportNameType::Decorated))
403             .then_some('_'),
404             DllCallingConvention::Fastcall(_) => Some('@'),
405         }
406     } else if !dll_import.is_fn && !mingw {
407         // For static variables, prefix with '_' on MSVC.
408         Some('_')
409     } else {
410         None
411     };
412     if let Some(prefix) = prefix {
413         decorated_name.push(prefix);
414     }
415 
416     decorated_name.push_str(name);
417 
418     if add_suffix && dll_import.is_fn {
419         match dll_import.calling_convention {
420             DllCallingConvention::C => {}
421             DllCallingConvention::Stdcall(arg_list_size)
422             | DllCallingConvention::Fastcall(arg_list_size) => {
423                 write!(&mut decorated_name, "@{}", arg_list_size).unwrap();
424             }
425             DllCallingConvention::Vectorcall(arg_list_size) => {
426                 write!(&mut decorated_name, "@@{}", arg_list_size).unwrap();
427             }
428         }
429     }
430 
431     decorated_name
432 }
433