1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_camel_case_types, non_snake_case)]
13 //! Code that is useful in various codegen modules.
15 use llvm::{self, True, False, Bool, BasicBlock, OperandBundleDef};
19 use type_of::LayoutLlvmExt;
21 use rustc_codegen_ssa::traits::*;
23 use rustc::ty::layout::{HasDataLayout, LayoutOf, self, TyLayout, Size};
24 use rustc::mir::interpret::{Scalar, AllocKind, Allocation};
25 use consts::const_alloc_to_llvm;
26 use rustc_codegen_ssa::mir::place::PlaceRef;
28 use libc::{c_uint, c_char};
30 use syntax::symbol::LocalInternedString;
31 use syntax::ast::Mutability;
33 pub use context::CodegenCx;
36 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
38 * An "extern" is an LLVM symbol we wind up emitting an undefined external
39 * reference to. This means "we don't have the thing in this compilation unit,
40 * please make sure you link it in at runtime". This could be a reference to
41 * C code found in a C library, or rust code found in a rust crate.
43 * Most "externs" are implicitly declared (automatically) as a result of a
44 * user declaring an extern _module_ dependency; this causes the rust driver
45 * to locate an extern crate, scan its compilation metadata, and emit extern
46 * declarations for any symbols used by the declaring crate.
48 * A "foreign" is an extern that references C (or other non-rust ABI) code.
49 * There is no metadata to scan for extern references so in these cases either
50 * a header-digester like bindgen, or manual function prototypes, have to
51 * serve as declarators. So these are usually given explicitly as prototype
52 * declarations, in rust code, with ABI attributes on them noting which ABI to
55 * An "upcall" is a foreign call generated by the compiler (not corresponding
56 * to any user-written call in the code) into the runtime library, to perform
57 * some helper task such as bringing a task to life, allocating memory, etc.
61 /// A structure representing an active landing pad for the duration of a basic
64 /// Each `Block` may contain an instance of this, indicating whether the block
65 /// is part of a landing pad or not. This is used to make decision about whether
66 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
67 /// use `invoke`) and also about various function call metadata.
69 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
70 /// just a bunch of `None` instances (not too interesting), but for MSVC
71 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
72 /// When inside of a landing pad, each function call in LLVM IR needs to be
73 /// annotated with which landing pad it's a part of. This is accomplished via
74 /// the `OperandBundleDef` value created for MSVC landing pads.
75 pub struct Funclet<'ll> {
76 cleanuppad: &'ll Value,
77 operand: OperandBundleDef<'ll>,
81 pub fn new(cleanuppad: &'ll Value) -> Self {
84 operand: OperandBundleDef::new("funclet", &[cleanuppad]),
88 pub fn cleanuppad(&self) -> &'ll Value {
92 pub fn bundle(&self) -> &OperandBundleDef<'ll> {
97 impl BackendTypes for CodegenCx<'ll, 'tcx> {
98 type Value = &'ll Value;
99 type BasicBlock = &'ll BasicBlock;
100 type Type = &'ll Type;
101 type Funclet = Funclet<'ll>;
103 type DIScope = &'ll llvm::debuginfo::DIScope;
106 impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
107 fn const_null(&self, t: &'ll Type) -> &'ll Value {
109 llvm::LLVMConstNull(t)
113 fn const_undef(&self, t: &'ll Type) -> &'ll Value {
115 llvm::LLVMGetUndef(t)
119 fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
121 llvm::LLVMConstInt(t, i as u64, True)
125 fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
127 llvm::LLVMConstInt(t, i, False)
131 fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
133 let words = [u as u64, (u >> 64) as u64];
134 llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
138 fn const_bool(&self, val: bool) -> &'ll Value {
139 self.const_uint(self.type_i1(), val as u64)
142 fn const_i32(&self, i: i32) -> &'ll Value {
143 self.const_int(self.type_i32(), i as i64)
146 fn const_u32(&self, i: u32) -> &'ll Value {
147 self.const_uint(self.type_i32(), i as u64)
150 fn const_u64(&self, i: u64) -> &'ll Value {
151 self.const_uint(self.type_i64(), i)
154 fn const_usize(&self, i: u64) -> &'ll Value {
155 let bit_size = self.data_layout().pointer_size.bits();
157 // make sure it doesn't overflow
158 assert!(i < (1<<bit_size));
161 self.const_uint(self.isize_ty, i)
164 fn const_u8(&self, i: u8) -> &'ll Value {
165 self.const_uint(self.type_i8(), i as u64)
170 s: LocalInternedString,
171 null_terminated: bool,
174 if let Some(&llval) = self.const_cstr_cache.borrow().get(&s) {
178 let sc = llvm::LLVMConstStringInContext(self.llcx,
179 s.as_ptr() as *const c_char,
181 !null_terminated as Bool);
182 let sym = self.generate_local_symbol_name("str");
183 let g = self.define_global(&sym[..], self.val_ty(sc)).unwrap_or_else(||{
184 bug!("symbol `{}` is already defined", sym);
186 llvm::LLVMSetInitializer(g, sc);
187 llvm::LLVMSetGlobalConstant(g, True);
188 llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
190 self.const_cstr_cache.borrow_mut().insert(s, g);
195 fn const_str_slice(&self, s: LocalInternedString) -> &'ll Value {
197 let cs = consts::ptrcast(self.const_cstr(s, false),
198 self.type_ptr_to(self.layout_of(self.tcx.mk_str()).llvm_type(self)));
199 self.const_fat_ptr(cs, self.const_usize(len as u64))
207 assert_eq!(abi::FAT_PTR_ADDR, 0);
208 assert_eq!(abi::FAT_PTR_EXTRA, 1);
209 self.const_struct(&[ptr, meta], false)
217 struct_in_context(self.llcx, elts, packed)
220 fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
222 return llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint);
226 fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
228 return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
232 fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
233 bytes_in_context(self.llcx, bytes)
236 fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
238 assert_eq!(idx as c_uint as u64, idx);
239 let us = &[idx as c_uint];
240 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
242 debug!("const_get_elt(v={:?}, idx={}, r={:?})",
249 fn const_get_real(&self, v: &'ll Value) -> Option<(f64, bool)> {
251 if self.is_const_real(v) {
252 let mut loses_info: llvm::Bool = ::std::mem::uninitialized();
253 let r = llvm::LLVMConstRealGetDouble(v, &mut loses_info);
254 let loses_info = if loses_info == 1 { true } else { false };
255 Some((r, loses_info))
262 fn const_to_uint(&self, v: &'ll Value) -> u64 {
264 llvm::LLVMConstIntGetZExtValue(v)
268 fn is_const_integral(&self, v: &'ll Value) -> bool {
270 llvm::LLVMIsAConstantInt(v).is_some()
274 fn is_const_real(&self, v: &'ll Value) -> bool {
276 llvm::LLVMIsAConstantFP(v).is_some()
280 fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
282 if self.is_const_integral(v) {
283 let (mut lo, mut hi) = (0u64, 0u64);
284 let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
287 Some(hi_lo_to_u128(lo, hi))
297 fn scalar_to_backend(
300 layout: &layout::Scalar,
303 let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() };
305 Scalar::Bits { size: 0, .. } => {
306 assert_eq!(0, layout.value.size(self).bytes());
307 self.const_undef(self.type_ix(0))
309 Scalar::Bits { bits, size } => {
310 assert_eq!(size as u64, layout.value.size(self).bytes());
311 let llval = self.const_uint_big(self.type_ix(bitsize), bits);
312 if layout.value == layout::Pointer {
313 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
315 self.const_bitcast(llval, llty)
318 Scalar::Ptr(ptr) => {
319 let alloc_type = self.tcx.alloc_map.lock().get(ptr.alloc_id);
320 let base_addr = match alloc_type {
321 Some(AllocKind::Memory(alloc)) => {
322 let init = const_alloc_to_llvm(self, alloc);
323 if alloc.mutability == Mutability::Mutable {
324 self.static_addr_of_mut(init, alloc.align, None)
326 self.static_addr_of(init, alloc.align, None)
329 Some(AllocKind::Function(fn_instance)) => {
330 self.get_fn(fn_instance)
332 Some(AllocKind::Static(def_id)) => {
333 assert!(self.tcx.is_static(def_id).is_some());
334 self.get_static(def_id)
336 None => bug!("missing allocation {:?}", ptr.alloc_id),
338 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
339 self.const_bitcast(base_addr, self.type_i8p()),
340 &self.const_usize(ptr.offset.bytes()),
343 if layout.value != layout::Pointer {
344 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
346 self.const_bitcast(llval, llty)
354 layout: TyLayout<'tcx>,
357 ) -> PlaceRef<'tcx, &'ll Value> {
358 let init = const_alloc_to_llvm(self, alloc);
359 let base_addr = self.static_addr_of(init, layout.align.abi, None);
361 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
362 self.const_bitcast(base_addr, self.type_i8p()),
363 &self.const_usize(offset.bytes()),
366 let llval = self.const_bitcast(llval, self.type_ptr_to(layout.llvm_type(self)));
367 PlaceRef::new_sized(llval, layout, alloc.align)
370 fn const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
371 consts::ptrcast(val, ty)
375 pub fn val_ty(v: &'ll Value) -> &'ll Type {
381 pub fn bytes_in_context(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
383 let ptr = bytes.as_ptr() as *const c_char;
384 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
388 pub fn struct_in_context(
389 llcx: &'a llvm::Context,
394 llvm::LLVMConstStructInContext(llcx,
395 elts.as_ptr(), elts.len() as c_uint,
401 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
402 ((hi as u128) << 64) | (lo as u128)