1 #![allow(non_camel_case_types, non_snake_case)]
3 //! Code that is useful in various codegen modules.
5 use crate::llvm::{self, True, False, Bool, BasicBlock, OperandBundleDef, ConstantInt};
7 use crate::type_::Type;
8 use crate::type_of::LayoutLlvmExt;
9 use crate::value::Value;
10 use rustc_codegen_ssa::traits::*;
14 use crate::consts::const_alloc_to_llvm;
15 use rustc::ty::layout::{HasDataLayout, LayoutOf, self, TyLayout, Size};
16 use rustc::mir::interpret::{Scalar, GlobalAlloc, Allocation};
17 use rustc_codegen_ssa::mir::place::PlaceRef;
19 use libc::{c_uint, c_char};
21 use syntax::symbol::Symbol;
22 use syntax::ast::Mutability;
24 pub use crate::context::CodegenCx;
27 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
29 * An "extern" is an LLVM symbol we wind up emitting an undefined external
30 * reference to. This means "we don't have the thing in this compilation unit,
31 * please make sure you link it in at runtime". This could be a reference to
32 * C code found in a C library, or rust code found in a rust crate.
34 * Most "externs" are implicitly declared (automatically) as a result of a
35 * user declaring an extern _module_ dependency; this causes the rust driver
36 * to locate an extern crate, scan its compilation metadata, and emit extern
37 * declarations for any symbols used by the declaring crate.
39 * A "foreign" is an extern that references C (or other non-rust ABI) code.
40 * There is no metadata to scan for extern references so in these cases either
41 * a header-digester like bindgen, or manual function prototypes, have to
42 * serve as declarators. So these are usually given explicitly as prototype
43 * declarations, in rust code, with ABI attributes on them noting which ABI to
46 * An "upcall" is a foreign call generated by the compiler (not corresponding
47 * to any user-written call in the code) into the runtime library, to perform
48 * some helper task such as bringing a task to life, allocating memory, etc.
52 /// A structure representing an active landing pad for the duration of a basic
55 /// Each `Block` may contain an instance of this, indicating whether the block
56 /// is part of a landing pad or not. This is used to make decision about whether
57 /// to emit `invoke` instructions (e.g., in a landing pad we don't continue to
58 /// use `invoke`) and also about various function call metadata.
60 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
61 /// just a bunch of `None` instances (not too interesting), but for MSVC
62 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
63 /// When inside of a landing pad, each function call in LLVM IR needs to be
64 /// annotated with which landing pad it's a part of. This is accomplished via
65 /// the `OperandBundleDef` value created for MSVC landing pads.
66 pub struct Funclet<'ll> {
67 cleanuppad: &'ll Value,
68 operand: OperandBundleDef<'ll>,
72 pub fn new(cleanuppad: &'ll Value) -> Self {
75 operand: OperandBundleDef::new("funclet", &[cleanuppad]),
79 pub fn cleanuppad(&self) -> &'ll Value {
83 pub fn bundle(&self) -> &OperandBundleDef<'ll> {
88 impl BackendTypes for CodegenCx<'ll, 'tcx> {
89 type Value = &'ll Value;
90 type Function = &'ll Value;
92 type BasicBlock = &'ll BasicBlock;
93 type Type = &'ll Type;
94 type Funclet = Funclet<'ll>;
96 type DIScope = &'ll llvm::debuginfo::DIScope;
99 impl CodegenCx<'ll, 'tcx> {
100 pub fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
102 return llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint);
106 pub fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
108 return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
112 pub fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
113 bytes_in_context(self.llcx, bytes)
119 null_terminated: bool,
122 if let Some(&llval) = self.const_cstr_cache.borrow().get(&s) {
126 let s_str = s.as_str();
127 let sc = llvm::LLVMConstStringInContext(self.llcx,
128 s_str.as_ptr() as *const c_char,
129 s_str.len() as c_uint,
130 !null_terminated as Bool);
131 let sym = self.generate_local_symbol_name("str");
132 let g = self.define_global(&sym[..], self.val_ty(sc)).unwrap_or_else(||{
133 bug!("symbol `{}` is already defined", sym);
135 llvm::LLVMSetInitializer(g, sc);
136 llvm::LLVMSetGlobalConstant(g, True);
137 llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
139 self.const_cstr_cache.borrow_mut().insert(s, g);
144 pub fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
146 assert_eq!(idx as c_uint as u64, idx);
147 let us = &[idx as c_uint];
148 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
150 debug!("const_get_elt(v={:?}, idx={}, r={:?})",
158 impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
159 fn const_null(&self, t: &'ll Type) -> &'ll Value {
161 llvm::LLVMConstNull(t)
165 fn const_undef(&self, t: &'ll Type) -> &'ll Value {
167 llvm::LLVMGetUndef(t)
171 fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
173 llvm::LLVMConstInt(t, i as u64, True)
177 fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
179 llvm::LLVMConstInt(t, i, False)
183 fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
185 let words = [u as u64, (u >> 64) as u64];
186 llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
190 fn const_bool(&self, val: bool) -> &'ll Value {
191 self.const_uint(self.type_i1(), val as u64)
194 fn const_i32(&self, i: i32) -> &'ll Value {
195 self.const_int(self.type_i32(), i as i64)
198 fn const_u32(&self, i: u32) -> &'ll Value {
199 self.const_uint(self.type_i32(), i as u64)
202 fn const_u64(&self, i: u64) -> &'ll Value {
203 self.const_uint(self.type_i64(), i)
206 fn const_usize(&self, i: u64) -> &'ll Value {
207 let bit_size = self.data_layout().pointer_size.bits();
209 // make sure it doesn't overflow
210 assert!(i < (1<<bit_size));
213 self.const_uint(self.isize_ty, i)
216 fn const_u8(&self, i: u8) -> &'ll Value {
217 self.const_uint(self.type_i8(), i as u64)
220 fn const_real(&self, t: &'ll Type, val: f64) -> &'ll Value {
221 unsafe { llvm::LLVMConstReal(t, val) }
224 fn const_str(&self, s: Symbol) -> (&'ll Value, &'ll Value) {
225 let len = s.as_str().len();
226 let cs = consts::ptrcast(self.const_cstr(s, false),
227 self.type_ptr_to(self.layout_of(self.tcx.mk_str()).llvm_type(self)));
228 (cs, self.const_usize(len as u64))
236 struct_in_context(self.llcx, elts, packed)
239 fn const_to_opt_uint(&self, v: &'ll Value) -> Option<u64> {
240 try_as_const_integral(v).map(|v| unsafe {
241 llvm::LLVMConstIntGetZExtValue(v)
245 fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
246 try_as_const_integral(v).and_then(|v| unsafe {
247 let (mut lo, mut hi) = (0u64, 0u64);
248 let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
250 success.then_some(hi_lo_to_u128(lo, hi))
254 fn scalar_to_backend(
257 layout: &layout::Scalar,
260 let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() };
262 Scalar::Raw { size: 0, .. } => {
263 assert_eq!(0, layout.value.size(self).bytes());
264 self.const_undef(self.type_ix(0))
266 Scalar::Raw { data, size } => {
267 assert_eq!(size as u64, layout.value.size(self).bytes());
268 let llval = self.const_uint_big(self.type_ix(bitsize), data);
269 if layout.value == layout::Pointer {
270 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
272 self.const_bitcast(llval, llty)
275 Scalar::Ptr(ptr) => {
276 let alloc_kind = self.tcx.alloc_map.lock().get(ptr.alloc_id);
277 let base_addr = match alloc_kind {
278 Some(GlobalAlloc::Memory(alloc)) => {
279 let init = const_alloc_to_llvm(self, alloc);
280 if alloc.mutability == Mutability::Mutable {
281 self.static_addr_of_mut(init, alloc.align, None)
283 self.static_addr_of(init, alloc.align, None)
286 Some(GlobalAlloc::Function(fn_instance)) => {
287 self.get_fn_addr(fn_instance)
289 Some(GlobalAlloc::Static(def_id)) => {
290 assert!(self.tcx.is_static(def_id));
291 self.get_static(def_id)
293 None => bug!("missing allocation {:?}", ptr.alloc_id),
295 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
296 self.const_bitcast(base_addr, self.type_i8p()),
297 &self.const_usize(ptr.offset.bytes()),
300 if layout.value != layout::Pointer {
301 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
303 self.const_bitcast(llval, llty)
311 layout: TyLayout<'tcx>,
314 ) -> PlaceRef<'tcx, &'ll Value> {
315 assert_eq!(alloc.align, layout.align.abi);
316 let llty = self.type_ptr_to(layout.llvm_type(self));
317 let llval = if layout.size == Size::ZERO {
318 let llval = self.const_usize(alloc.align.bytes());
319 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
321 let init = const_alloc_to_llvm(self, alloc);
322 let base_addr = self.static_addr_of(init, alloc.align, None);
324 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
325 self.const_bitcast(base_addr, self.type_i8p()),
326 &self.const_usize(offset.bytes()),
329 self.const_bitcast(llval, llty)
331 PlaceRef::new_sized(llval, layout)
334 fn const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
335 consts::ptrcast(val, ty)
339 pub fn val_ty(v: &'ll Value) -> &'ll Type {
345 pub fn bytes_in_context(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
347 let ptr = bytes.as_ptr() as *const c_char;
348 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
352 pub fn struct_in_context(
353 llcx: &'a llvm::Context,
358 llvm::LLVMConstStructInContext(llcx,
359 elts.as_ptr(), elts.len() as c_uint,
365 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
366 ((hi as u128) << 64) | (lo as u128)
369 fn try_as_const_integral(v: &'ll Value) -> Option<&'ll ConstantInt> {
371 llvm::LLVMIsAConstantInt(v)