1use 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, PointerArithmetic, 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, Type, Value};
24
25pub(crate) struct Funclet<'ll> {
66 cleanuppad: &'ll Value,
67 operand: llvm::OperandBundleBox<'ll>,
68}
69
70impl<'ll> Funclet<'ll> {
71 pub(crate) fn new(cleanuppad: &'ll Value) -> Self {
72 Funclet { cleanuppad, operand: llvm::OperandBundleBox::new("funclet", &[cleanuppad]) }
73 }
74
75 pub(crate) fn cleanuppad(&self) -> &'ll Value {
76 self.cleanuppad
77 }
78
79 pub(crate) fn bundle(&self) -> &llvm::OperandBundle<'ll> {
80 self.operand.as_ref()
81 }
82}
83
84impl<'ll, CX: Borrow<SCx<'ll>>> BackendTypes for GenericCx<'ll, CX> {
85 type Value = &'ll Value;
86 type Metadata = &'ll Metadata;
87 type Function = &'ll Value;
89
90 type BasicBlock = &'ll BasicBlock;
91 type Type = &'ll Type;
92 type Funclet = Funclet<'ll>;
93
94 type DIScope = &'ll llvm::debuginfo::DIScope;
95 type DILocation = &'ll llvm::debuginfo::DILocation;
96 type DIVariable = &'ll llvm::debuginfo::DIVariable;
97}
98
99impl<'ll, CX: Borrow<SCx<'ll>>> GenericCx<'ll, CX> {
100 pub(crate) fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
101 let len = u64::try_from(elts.len()).expect("LLVMConstArray2 elements len overflow");
102 unsafe { llvm::LLVMConstArray2(ty, elts.as_ptr(), len) }
103 }
104
105 pub(crate) fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
106 bytes_in_context(self.llcx(), bytes)
107 }
108
109 pub(crate) fn null_terminate_const_bytes(&self, bytes: &[u8]) -> &'ll Value {
110 null_terminate_bytes_in_context(self.llcx(), bytes)
111 }
112
113 pub(crate) fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
114 unsafe {
115 let idx = c_uint::try_from(idx).expect("LLVMGetAggregateElement index overflow");
116 let r = llvm::LLVMGetAggregateElement(v, idx).unwrap();
117
118 debug!("const_get_elt(v={:?}, idx={}, r={:?})", v, idx, r);
119
120 r
121 }
122 }
123
124 pub(crate) fn const_null(&self, t: &'ll Type) -> &'ll Value {
125 unsafe { llvm::LLVMConstNull(t) }
126 }
127}
128
129impl<'ll, 'tcx> ConstCodegenMethods for CodegenCx<'ll, 'tcx> {
130 fn const_null(&self, t: &'ll Type) -> &'ll Value {
131 unsafe { llvm::LLVMConstNull(t) }
132 }
133
134 fn const_undef(&self, t: &'ll Type) -> &'ll Value {
135 unsafe { llvm::LLVMGetUndef(t) }
136 }
137
138 fn const_poison(&self, t: &'ll Type) -> &'ll Value {
139 unsafe { llvm::LLVMGetPoison(t) }
140 }
141
142 fn const_bool(&self, val: bool) -> &'ll Value {
143 self.const_uint(self.type_i1(), val as u64)
144 }
145
146 fn const_i8(&self, i: i8) -> &'ll Value {
147 self.const_int(self.type_i8(), i as i64)
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_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
159 debug_assert!(
160 self.type_kind(t) == TypeKind::Integer,
161 "only allows integer types in const_int"
162 );
163 unsafe { llvm::LLVMConstInt(t, i as u64, TRUE) }
164 }
165
166 fn const_u8(&self, i: u8) -> &'ll Value {
167 self.const_uint(self.type_i8(), i as u64)
168 }
169
170 fn const_u32(&self, i: u32) -> &'ll Value {
171 self.const_uint(self.type_i32(), i as u64)
172 }
173
174 fn const_u64(&self, i: u64) -> &'ll Value {
175 self.const_uint(self.type_i64(), i)
176 }
177
178 fn const_u128(&self, i: u128) -> &'ll Value {
179 self.const_uint_big(self.type_i128(), i)
180 }
181
182 fn const_usize(&self, i: u64) -> &'ll Value {
183 let bit_size = self.data_layout().pointer_size().bits();
184 if bit_size < 64 {
185 assert!(i < (1 << bit_size));
187 }
188
189 self.const_uint(self.isize_ty, i)
190 }
191
192 fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
193 debug_assert!(
194 self.type_kind(t) == TypeKind::Integer,
195 "only allows integer types in const_uint"
196 );
197 unsafe { llvm::LLVMConstInt(t, i, FALSE) }
198 }
199
200 fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
201 debug_assert!(
202 self.type_kind(t) == TypeKind::Integer,
203 "only allows integer types in const_uint_big"
204 );
205 unsafe {
206 let words = [u as u64, (u >> 64) as u64];
207 llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
208 }
209 }
210
211 fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
212 unsafe { llvm::LLVMConstReal(t, val) }
213 }
214
215 fn const_str(&self, s: &str) -> (&'ll Value, &'ll Value) {
216 let mut const_str_cache = self.const_str_cache.borrow_mut();
217 let str_global = const_str_cache.get(s).copied().unwrap_or_else(|| {
218 let sc = self.const_bytes(s.as_bytes());
219 let sym = self.generate_local_symbol_name("str");
220 let g = self.define_global(&sym, self.val_ty(sc)).unwrap_or_else(|| {
221 bug!("symbol `{}` is already defined", sym);
222 });
223 llvm::set_initializer(g, sc);
224
225 llvm::set_global_constant(g, true);
226 llvm::set_unnamed_address(g, llvm::UnnamedAddr::Global);
227
228 llvm::set_linkage(g, llvm::Linkage::InternalLinkage);
229 let g = self.const_pointercast(g, self.type_ptr());
231 const_str_cache.insert(s.to_owned(), g);
232 g
233 });
234 let len = s.len();
235 (str_global, self.const_usize(len as u64))
236 }
237
238 fn const_struct(&self, elts: &[&'ll Value], packed: bool) -> &'ll Value {
239 struct_in_context(self.llcx, elts, packed)
240 }
241
242 fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
243 let len = c_uint::try_from(elts.len()).expect("LLVMConstVector elements len overflow");
244 unsafe { llvm::LLVMConstVector(elts.as_ptr(), len) }
245 }
246
247 fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
248 try_as_const_integral(v).and_then(|v| unsafe {
249 let mut i = 0u64;
250 let success = llvm::LLVMRustConstIntGetZExtValue(v, &mut i);
251 success.then_some(i)
252 })
253 }
254
255 fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
256 try_as_const_integral(v).and_then(|v| unsafe {
257 let (mut lo, mut hi) = (0u64, 0u64);
258 let success = llvm::LLVMRustConstInt128Get(v, sign_ext, &mut hi, &mut lo);
259 success.then_some(hi_lo_to_u128(lo, hi))
260 })
261 }
262
263 fn scalar_to_backend(&self, cv: Scalar, layout: abi::Scalar, llty: &'ll Type) -> &'ll Value {
264 let bitsize = if layout.is_bool() { 1 } else { layout.size(self).bits() };
265 match cv {
266 Scalar::Int(int) => {
267 let data = int.to_bits(layout.size(self));
268 let llval = self.const_uint_big(self.type_ix(bitsize), data);
269 if matches!(layout.primitive(), Pointer(_)) {
270 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
271 } else {
272 self.const_bitcast(llval, llty)
273 }
274 }
275 Scalar::Ptr(ptr, _size) => {
276 let (prov, offset) = ptr.prov_and_relative_offset();
277 let global_alloc = self.tcx.global_alloc(prov.alloc_id());
278 let base_addr = match global_alloc {
279 GlobalAlloc::Memory(alloc) => {
280 if alloc.inner().len() == 0 {
284 let val = alloc.inner().align.bytes().wrapping_add(offset.bytes());
285 let llval = self.const_usize(self.tcx.truncate_to_target_usize(val));
286 return if matches!(layout.primitive(), Pointer(_)) {
287 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
288 } else {
289 self.const_bitcast(llval, llty)
290 };
291 } else {
292 let init =
293 const_alloc_to_llvm(self, alloc.inner(), false);
294 let alloc = alloc.inner();
295 let value = match alloc.mutability {
296 Mutability::Mut => self.static_addr_of_mut(init, alloc.align, None),
297 _ => self.static_addr_of_impl(init, alloc.align, None),
298 };
299 if !self.sess().fewer_names() && llvm::get_value_name(value).is_empty()
300 {
301 let hash = self.tcx.with_stable_hashing_context(|mut hcx| {
302 let mut hasher = StableHasher::new();
303 alloc.hash_stable(&mut hcx, &mut hasher);
304 hasher.finish::<Hash128>()
305 });
306 llvm::set_value_name(
307 value,
308 format!("alloc_{hash:032x}").as_bytes(),
309 );
310 }
311 value
312 }
313 }
314 GlobalAlloc::Function { instance, .. } => self.get_fn_addr(instance),
315 GlobalAlloc::VTable(ty, dyn_ty) => {
316 let alloc = self
317 .tcx
318 .global_alloc(self.tcx.vtable_allocation((
319 ty,
320 dyn_ty.principal().map(|principal| {
321 self.tcx.instantiate_bound_regions_with_erased(principal)
322 }),
323 )))
324 .unwrap_memory();
325 let init = const_alloc_to_llvm(self, alloc.inner(), false);
326 self.static_addr_of_impl(init, alloc.inner().align, None)
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)
332 }
333 GlobalAlloc::TypeId { .. } => {
334 let llval = self.const_usize(offset.bytes());
336 return unsafe { llvm::LLVMConstIntToPtr(llval, llty) };
337 }
338 };
339 let base_addr_space = global_alloc.address_space(self);
340 let llval = unsafe {
341 llvm::LLVMConstInBoundsGEP2(
342 self.type_i8(),
343 self.const_pointercast(base_addr, self.type_ptr_ext(base_addr_space)),
345 &self.const_usize(offset.bytes()),
346 1,
347 )
348 };
349 if !matches!(layout.primitive(), Pointer(_)) {
350 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
351 } else {
352 self.const_bitcast(llval, llty)
353 }
354 }
355 }
356 }
357
358 fn const_data_from_alloc(&self, alloc: ConstAllocation<'_>) -> Self::Value {
359 const_alloc_to_llvm(self, alloc.inner(), false)
360 }
361
362 fn const_ptr_byte_offset(&self, base_addr: Self::Value, offset: abi::Size) -> Self::Value {
363 unsafe {
364 llvm::LLVMConstInBoundsGEP2(
365 self.type_i8(),
366 base_addr,
367 &self.const_usize(offset.bytes()),
368 1,
369 )
370 }
371 }
372}
373
374pub(crate) fn val_ty(v: &Value) -> &Type {
376 unsafe { llvm::LLVMTypeOf(v) }
377}
378
379pub(crate) fn bytes_in_context<'ll>(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
380 unsafe {
381 let ptr = bytes.as_ptr() as *const c_char;
382 llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), TRUE)
383 }
384}
385
386pub(crate) fn null_terminate_bytes_in_context<'ll>(
387 llcx: &'ll llvm::Context,
388 bytes: &[u8],
389) -> &'ll Value {
390 unsafe {
391 let ptr = bytes.as_ptr() as *const c_char;
392 llvm::LLVMConstStringInContext2(llcx, ptr, bytes.len(), FALSE)
393 }
394}
395
396pub(crate) fn named_struct<'ll>(ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
397 let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
398 unsafe { llvm::LLVMConstNamedStruct(ty, elts.as_ptr(), len) }
399}
400
401fn struct_in_context<'ll>(
402 llcx: &'ll llvm::Context,
403 elts: &[&'ll Value],
404 packed: bool,
405) -> &'ll Value {
406 let len = c_uint::try_from(elts.len()).expect("LLVMConstStructInContext elements len overflow");
407 unsafe { llvm::LLVMConstStructInContext(llcx, elts.as_ptr(), len, packed.to_llvm_bool()) }
408}
409
410#[inline]
411fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
412 ((hi as u128) << 64) | (lo as u128)
413}
414
415fn try_as_const_integral(v: &Value) -> Option<&ConstantInt> {
416 unsafe { llvm::LLVMIsAConstantInt(v) }
417}
418
419pub(crate) fn get_dllimport<'tcx>(
420 tcx: TyCtxt<'tcx>,
421 id: DefId,
422 name: &str,
423) -> Option<&'tcx DllImport> {
424 tcx.native_library(id)
425 .and_then(|lib| lib.dll_imports.iter().find(|di| di.name.as_str() == name))
426}
427
428pub(crate) trait AsCCharPtr {
430 fn as_c_char_ptr(&self) -> *const c_char;
432}
433
434impl AsCCharPtr for str {
435 fn as_c_char_ptr(&self) -> *const c_char {
436 self.as_ptr().cast()
437 }
438}
439
440impl AsCCharPtr for [u8] {
441 fn as_c_char_ptr(&self) -> *const c_char {
442 self.as_ptr().cast()
443 }
444}