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 trans modules.
16 use llvm::{ValueRef, ContextRef, TypeKind};
17 use llvm::{True, False, Bool, OperandBundleDef};
18 use rustc::hir::def_id::DefId;
19 use rustc::hir::map::DefPathData;
20 use middle::lang_items::LangItem;
29 use rustc::ty::{self, Ty, TyCtxt};
30 use rustc::ty::layout::{Layout, LayoutTyper};
31 use rustc::ty::subst::{Subst, Substs};
34 use libc::{c_uint, c_char};
38 use syntax::symbol::InternedString;
41 pub use context::{CrateContext, SharedCrateContext};
43 pub fn type_is_fat_ptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
44 if let Layout::FatPointer { .. } = *ccx.layout_of(ty) {
51 pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
52 let layout = ccx.layout_of(ty);
54 Layout::CEnum { .. } |
55 Layout::Scalar { .. } |
56 Layout::Vector { .. } => true,
58 Layout::FatPointer { .. } => false,
60 Layout::Array { .. } |
61 Layout::Univariant { .. } |
62 Layout::General { .. } |
63 Layout::UntaggedUnion { .. } |
64 Layout::RawNullablePointer { .. } |
65 Layout::StructWrappedNullablePointer { .. } => {
66 !layout.is_unsized() && layout.size(ccx).bytes() == 0
71 /// Returns Some([a, b]) if the type has a pair of fields with types a and b.
72 pub fn type_pair_fields<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>)
73 -> Option<[Ty<'tcx>; 2]> {
75 ty::TyAdt(adt, substs) => {
76 assert_eq!(adt.variants.len(), 1);
77 let fields = &adt.variants[0].fields;
78 if fields.len() != 2 {
81 Some([monomorphize::field_ty(ccx.tcx(), substs, &fields[0]),
82 monomorphize::field_ty(ccx.tcx(), substs, &fields[1])])
84 ty::TyClosure(def_id, substs) => {
85 let mut tys = substs.upvar_tys(def_id, ccx.tcx());
86 tys.next().and_then(|first_ty| tys.next().and_then(|second_ty| {
87 if tys.next().is_some() {
90 Some([first_ty, second_ty])
94 ty::TyTuple(tys, _) => {
98 Some([tys[0], tys[1]])
104 /// Returns true if the type is represented as a pair of immediates.
105 pub fn type_is_imm_pair<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>)
107 match *ccx.layout_of(ty) {
108 Layout::FatPointer { .. } => true,
109 Layout::Univariant { ref variant, .. } => {
110 // There must be only 2 fields.
111 if variant.offsets.len() != 2 {
115 match type_pair_fields(ccx, ty) {
117 type_is_immediate(ccx, a) && type_is_immediate(ccx, b)
126 /// Identify types which have size zero at runtime.
127 pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
128 let layout = ccx.layout_of(ty);
129 !layout.is_unsized() && layout.size(ccx).bytes() == 0
133 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
135 * An "extern" is an LLVM symbol we wind up emitting an undefined external
136 * reference to. This means "we don't have the thing in this compilation unit,
137 * please make sure you link it in at runtime". This could be a reference to
138 * C code found in a C library, or rust code found in a rust crate.
140 * Most "externs" are implicitly declared (automatically) as a result of a
141 * user declaring an extern _module_ dependency; this causes the rust driver
142 * to locate an extern crate, scan its compilation metadata, and emit extern
143 * declarations for any symbols used by the declaring crate.
145 * A "foreign" is an extern that references C (or other non-rust ABI) code.
146 * There is no metadata to scan for extern references so in these cases either
147 * a header-digester like bindgen, or manual function prototypes, have to
148 * serve as declarators. So these are usually given explicitly as prototype
149 * declarations, in rust code, with ABI attributes on them noting which ABI to
152 * An "upcall" is a foreign call generated by the compiler (not corresponding
153 * to any user-written call in the code) into the runtime library, to perform
154 * some helper task such as bringing a task to life, allocating memory, etc.
158 /// A structure representing an active landing pad for the duration of a basic
161 /// Each `Block` may contain an instance of this, indicating whether the block
162 /// is part of a landing pad or not. This is used to make decision about whether
163 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
164 /// use `invoke`) and also about various function call metadata.
166 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
167 /// just a bunch of `None` instances (not too interesting), but for MSVC
168 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
169 /// When inside of a landing pad, each function call in LLVM IR needs to be
170 /// annotated with which landing pad it's a part of. This is accomplished via
171 /// the `OperandBundleDef` value created for MSVC landing pads.
173 cleanuppad: ValueRef,
174 operand: OperandBundleDef,
178 pub fn new(cleanuppad: ValueRef) -> Funclet {
180 cleanuppad: cleanuppad,
181 operand: OperandBundleDef::new("funclet", &[cleanuppad]),
185 pub fn cleanuppad(&self) -> ValueRef {
189 pub fn bundle(&self) -> &OperandBundleDef {
194 impl Clone for Funclet {
195 fn clone(&self) -> Funclet {
197 cleanuppad: self.cleanuppad,
198 operand: OperandBundleDef::new("funclet", &[self.cleanuppad]),
203 pub fn val_ty(v: ValueRef) -> Type {
205 Type::from_ref(llvm::LLVMTypeOf(v))
209 // LLVM constant constructors.
210 pub fn C_null(t: Type) -> ValueRef {
212 llvm::LLVMConstNull(t.to_ref())
216 pub fn C_undef(t: Type) -> ValueRef {
218 llvm::LLVMGetUndef(t.to_ref())
222 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
224 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
228 pub fn C_big_integral(t: Type, u: u128) -> ValueRef {
230 let words = [u as u64, u.wrapping_shr(64) as u64];
231 llvm::LLVMConstIntOfArbitraryPrecision(t.to_ref(), 2, words.as_ptr())
235 pub fn C_floating_f64(f: f64, t: Type) -> ValueRef {
237 llvm::LLVMConstReal(t.to_ref(), f)
241 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
242 C_struct(ccx, &[], false)
245 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
246 C_integral(Type::i1(ccx), val as u64, false)
249 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
250 C_integral(Type::i32(ccx), i as u64, true)
253 pub fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef {
254 C_integral(Type::i32(ccx), i as u64, false)
257 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
258 C_integral(Type::i64(ccx), i, false)
261 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
264 let bit_size = machine::llbitsize_of_real(ccx, ccx.int_type());
267 // make sure it doesn't overflow
268 assert!(v < (1<<bit_size));
271 C_integral(ccx.int_type(), v, false)
274 pub trait AsI64 { fn as_i64(self) -> i64; }
275 pub trait AsU64 { fn as_u64(self) -> u64; }
277 // FIXME: remove the intptr conversions, because they
278 // are host-architecture-dependent
279 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
280 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
281 impl AsI64 for isize { fn as_i64(self) -> i64 { self as i64 }}
283 impl AsU64 for u64 { fn as_u64(self) -> u64 { self as u64 }}
284 impl AsU64 for u32 { fn as_u64(self) -> u64 { self as u64 }}
285 impl AsU64 for usize { fn as_u64(self) -> u64 { self as u64 }}
287 pub fn C_u8(ccx: &CrateContext, i: u8) -> ValueRef {
288 C_integral(Type::i8(ccx), i as u64, false)
292 // This is a 'c-like' raw string, which differs from
293 // our boxed-and-length-annotated strings.
294 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
296 if let Some(&llval) = cx.const_cstr_cache().borrow().get(&s) {
300 let sc = llvm::LLVMConstStringInContext(cx.llcx(),
301 s.as_ptr() as *const c_char,
303 !null_terminated as Bool);
304 let sym = cx.generate_local_symbol_name("str");
305 let g = declare::define_global(cx, &sym[..], val_ty(sc)).unwrap_or_else(||{
306 bug!("symbol `{}` is already defined", sym);
308 llvm::LLVMSetInitializer(g, sc);
309 llvm::LLVMSetGlobalConstant(g, True);
310 llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
312 cx.const_cstr_cache().borrow_mut().insert(s, g);
317 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
318 // you will be kicked off fast isel. See issue #4352 for an example of this.
319 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
321 let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
322 C_named_struct(cx.str_slice_type(), &[cs, C_uint(cx, len)])
325 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
326 C_struct_in_context(cx.llcx(), elts, packed)
329 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
331 llvm::LLVMConstStructInContext(llcx,
332 elts.as_ptr(), elts.len() as c_uint,
337 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
339 llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
343 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
345 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
349 pub fn C_vector(elts: &[ValueRef]) -> ValueRef {
351 return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
355 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
356 C_bytes_in_context(cx.llcx(), bytes)
359 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
361 let ptr = bytes.as_ptr() as *const c_char;
362 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
366 pub fn const_get_elt(v: ValueRef, us: &[c_uint])
369 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
371 debug!("const_get_elt(v={:?}, us={:?}, r={:?})",
372 Value(v), us, Value(r));
378 pub fn const_to_uint(v: ValueRef) -> u64 {
380 llvm::LLVMConstIntGetZExtValue(v)
384 fn is_const_integral(v: ValueRef) -> bool {
386 !llvm::LLVMIsAConstantInt(v).is_null()
391 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
392 ((hi as u128) << 64) | (lo as u128)
395 pub fn const_to_opt_u128(v: ValueRef, sign_ext: bool) -> Option<u128> {
397 if is_const_integral(v) {
398 let (mut lo, mut hi) = (0u64, 0u64);
399 let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
400 &mut hi as *mut u64, &mut lo as *mut u64);
402 Some(hi_lo_to_u128(lo, hi))
412 pub fn is_undef(val: ValueRef) -> bool {
414 llvm::LLVMIsUndef(val) != False
418 #[allow(dead_code)] // potentially useful
419 pub fn is_null(val: ValueRef) -> bool {
421 llvm::LLVMIsNull(val) != False
425 pub fn langcall(tcx: TyCtxt,
430 match tcx.lang_items.require(li) {
433 let msg = format!("{} {}", msg, s);
435 Some(span) => tcx.sess.span_fatal(span, &msg[..]),
436 None => tcx.sess.fatal(&msg[..]),
442 // To avoid UB from LLVM, these two functions mask RHS with an
443 // appropriate mask unconditionally (i.e. the fallback behavior for
444 // all shifts). For 32- and 64-bit types, this matches the semantics
445 // of Java. (See related discussion on #1877 and #10183.)
447 pub fn build_unchecked_lshift<'a, 'tcx>(
448 bcx: &Builder<'a, 'tcx>,
452 let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
453 // #1877, #10183: Ensure that input is always valid
454 let rhs = shift_mask_rhs(bcx, rhs);
458 pub fn build_unchecked_rshift<'a, 'tcx>(
459 bcx: &Builder<'a, 'tcx>, lhs_t: Ty<'tcx>, lhs: ValueRef, rhs: ValueRef
461 let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
462 // #1877, #10183: Ensure that input is always valid
463 let rhs = shift_mask_rhs(bcx, rhs);
464 let is_signed = lhs_t.is_signed();
472 fn shift_mask_rhs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, rhs: ValueRef) -> ValueRef {
473 let rhs_llty = val_ty(rhs);
474 bcx.and(rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false))
477 pub fn shift_mask_val<'a, 'tcx>(
478 bcx: &Builder<'a, 'tcx>,
483 let kind = llty.kind();
485 TypeKind::Integer => {
486 // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
487 let val = llty.int_width() - 1;
489 C_integral(mask_llty, !val, true)
491 C_integral(mask_llty, val, false)
494 TypeKind::Vector => {
495 let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
496 bcx.vector_splat(mask_llty.vector_length(), mask)
498 _ => bug!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
502 pub fn ty_fn_sig<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
504 -> ty::PolyFnSig<'tcx>
507 ty::TyFnDef(_, _, sig) => sig,
508 // Shims currently have type TyFnPtr. Not sure this should remain.
509 ty::TyFnPtr(sig) => sig,
510 ty::TyClosure(def_id, substs) => {
512 let sig = tcx.closure_type(def_id).subst(tcx, substs.substs);
514 let env_region = ty::ReLateBound(ty::DebruijnIndex::new(1), ty::BrEnv);
515 let env_ty = match tcx.closure_kind(def_id) {
516 ty::ClosureKind::Fn => tcx.mk_imm_ref(tcx.mk_region(env_region), ty),
517 ty::ClosureKind::FnMut => tcx.mk_mut_ref(tcx.mk_region(env_region), ty),
518 ty::ClosureKind::FnOnce => ty,
521 sig.map_bound(|sig| tcx.mk_fn_sig(
522 iter::once(env_ty).chain(sig.inputs().iter().cloned()),
529 _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
533 pub fn requests_inline<'a, 'tcx>(
534 tcx: TyCtxt<'a, 'tcx, 'tcx>,
535 instance: &ty::Instance<'tcx>
537 if is_inline_instance(tcx, instance) {
540 attr::requests_inline(&instance.def.attrs(tcx)[..])
543 pub fn is_inline_instance<'a, 'tcx>(
544 tcx: TyCtxt<'a, 'tcx, 'tcx>,
545 instance: &ty::Instance<'tcx>
547 let def_id = match instance.def {
548 ty::InstanceDef::Item(def_id) => def_id,
549 ty::InstanceDef::DropGlue(_, Some(_)) => return false,
552 match tcx.def_key(def_id).disambiguated_data.data {
553 DefPathData::StructCtor |
554 DefPathData::EnumVariant(..) |
555 DefPathData::ClosureExpr => true,
560 /// Given a DefId and some Substs, produces the monomorphic item type.
561 pub fn def_ty<'a, 'tcx>(shared: &SharedCrateContext<'a, 'tcx>,
563 substs: &'tcx Substs<'tcx>)
566 let ty = shared.tcx().type_of(def_id);
567 shared.tcx().trans_apply_param_substs(substs, &ty)
570 /// Return the substituted type of an instance.
571 pub fn instance_ty<'a, 'tcx>(shared: &SharedCrateContext<'a, 'tcx>,
572 instance: &ty::Instance<'tcx>)
575 let ty = instance.def.def_ty(shared.tcx());
576 shared.tcx().trans_apply_param_substs(instance.substs, &ty)