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 // trans.rs: Translate the completed AST to the LLVM IR.
13 // Some functions here, such as trans_block and trans_expr, return a value --
14 // the result of the translation to LLVM -- while others, such as trans_fn,
15 // trans_impl, and trans_item, are called only for the side effect of adding a
16 // particular definition to the LLVM IR output we're producing.
18 // Hopefully useful general knowledge about trans:
20 // * There's no way to find out the Ty type of a ValueRef. Doing so
21 // would be "trying to get the eggs out of an omelette" (credit:
22 // pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23 // but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
26 #![allow(non_camel_case_types)]
28 pub use self::ValueOrigin::*;
30 use super::CrateTranslation;
31 use super::ModuleTranslation;
33 use back::link::{mangle_exported_name};
34 use back::{link, abi};
36 use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param};
38 use metadata::{csearch, encoder, loader};
39 use middle::astencode;
41 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
42 use middle::weak_lang_items;
43 use middle::subst::{Subst, Substs};
44 use middle::ty::{self, Ty, ClosureTyper};
45 use session::config::{self, NoDebugInfo};
50 use trans::builder::{Builder, noname};
52 use trans::cleanup::CleanupMethods;
55 use trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_integral};
56 use trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
57 use trans::common::{CrateContext, ExternMap, FunctionContext};
58 use trans::common::{Result, NodeIdAndSpan};
59 use trans::common::{node_id_type, return_type_is_void};
60 use trans::common::{tydesc_info, type_is_immediate};
61 use trans::common::{type_is_zero_size, val_ty};
64 use trans::context::SharedCrateContext;
65 use trans::controlflow;
67 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
74 use trans::machine::{llsize_of, llsize_of_real};
76 use trans::monomorphize;
78 use trans::type_::Type;
80 use trans::type_of::*;
81 use trans::value::Value;
82 use util::common::indenter;
83 use util::ppaux::{Repr, ty_to_string};
84 use util::sha2::Sha256;
85 use util::nodemap::NodeMap;
87 use arena::TypedArena;
88 use libc::{c_uint, uint64_t};
89 use std::ffi::{CStr, CString};
90 use std::cell::{Cell, RefCell};
91 use std::collections::HashSet;
95 use std::{i8, i16, i32, i64};
96 use syntax::abi::{Rust, RustCall, RustIntrinsic, Abi};
97 use syntax::ast_util::local_def;
98 use syntax::attr::AttrMetaMethods;
100 use syntax::codemap::Span;
101 use syntax::parse::token::InternedString;
102 use syntax::visit::Visitor;
104 use syntax::{ast, ast_util, ast_map};
107 static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
112 pub fn with_insn_ctxt<F>(blk: F) where
113 F: FnOnce(&[&'static str]),
115 TASK_LOCAL_INSN_KEY.with(move |slot| {
116 slot.borrow().as_ref().map(move |s| blk(s));
120 pub fn init_insn_ctxt() {
121 TASK_LOCAL_INSN_KEY.with(|slot| {
122 *slot.borrow_mut() = Some(Vec::new());
126 pub struct _InsnCtxt {
127 _cannot_construct_outside_of_this_module: ()
131 impl Drop for _InsnCtxt {
133 TASK_LOCAL_INSN_KEY.with(|slot| {
134 match slot.borrow_mut().as_mut() {
135 Some(ctx) => { ctx.pop(); }
142 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
143 debug!("new InsnCtxt: {}", s);
144 TASK_LOCAL_INSN_KEY.with(|slot| {
145 match slot.borrow_mut().as_mut() {
146 Some(ctx) => ctx.push(s),
150 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
153 pub struct StatRecorder<'a, 'tcx: 'a> {
154 ccx: &'a CrateContext<'a, 'tcx>,
155 name: Option<String>,
159 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
160 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String)
161 -> StatRecorder<'a, 'tcx> {
162 let istart = ccx.stats().n_llvm_insns.get();
172 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
174 if self.ccx.sess().trans_stats() {
175 let iend = self.ccx.stats().n_llvm_insns.get();
176 self.ccx.stats().fn_stats.borrow_mut().push((self.name.take().unwrap(),
177 iend - self.istart));
178 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
179 // Reset LLVM insn count to avoid compound costs.
180 self.ccx.stats().n_llvm_insns.set(self.istart);
185 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
186 pub fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
187 ty: Type, output: ty::FnOutput) -> ValueRef {
189 let buf = CString::new(name).unwrap();
190 let llfn: ValueRef = unsafe {
191 llvm::LLVMGetOrInsertFunction(ccx.llmod(), buf.as_ptr(), ty.to_ref())
194 // diverging functions may unwind, but can never return normally
195 if output == ty::FnDiverging {
196 llvm::SetFunctionAttribute(llfn, llvm::NoReturnAttribute);
199 if ccx.tcx().sess.opts.cg.no_redzone
200 .unwrap_or(ccx.tcx().sess.target.target.options.disable_redzone) {
201 llvm::SetFunctionAttribute(llfn, llvm::NoRedZoneAttribute)
204 llvm::SetFunctionCallConv(llfn, cc);
205 // Function addresses in Rust are never significant, allowing functions to be merged.
206 llvm::SetUnnamedAddr(llfn, true);
208 if ccx.is_split_stack_supported() && !ccx.sess().opts.cg.no_stack_check {
209 set_split_stack(llfn);
215 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
216 pub fn decl_cdecl_fn(ccx: &CrateContext,
219 output: Ty) -> ValueRef {
220 decl_fn(ccx, name, llvm::CCallConv, ty, ty::FnConverging(output))
223 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
224 pub fn get_extern_fn(ccx: &CrateContext,
225 externs: &mut ExternMap,
231 match externs.get(name) {
232 Some(n) => return *n,
235 let f = decl_fn(ccx, name, cc, ty, ty::FnConverging(output));
236 externs.insert(name.to_string(), f);
240 fn get_extern_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>,
241 name: &str, did: ast::DefId) -> ValueRef {
242 match ccx.externs().borrow().get(name) {
243 Some(n) => return *n,
247 let f = decl_rust_fn(ccx, fn_ty, name);
249 let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
250 set_llvm_fn_attrs(ccx, &attrs[..], f);
252 ccx.externs().borrow_mut().insert(name.to_string(), f);
256 pub fn self_type_for_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
257 closure_id: ast::DefId,
261 let closure_kind = ccx.tcx().closure_kind(closure_id);
263 ty::FnClosureKind => {
264 ty::mk_imm_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
266 ty::FnMutClosureKind => {
267 ty::mk_mut_rptr(ccx.tcx(), ccx.tcx().mk_region(ty::ReStatic), fn_ty)
269 ty::FnOnceClosureKind => fn_ty
273 pub fn kind_for_closure(ccx: &CrateContext, closure_id: ast::DefId) -> ty::ClosureKind {
274 ccx.tcx().closure_kinds.borrow()[closure_id]
277 pub fn decl_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
278 fn_ty: Ty<'tcx>, name: &str) -> ValueRef {
279 debug!("decl_rust_fn(fn_ty={}, name={:?})",
280 fn_ty.repr(ccx.tcx()),
283 let fn_ty = monomorphize::normalize_associated_type(ccx.tcx(), &fn_ty);
285 debug!("decl_rust_fn: fn_ty={} (after normalized associated types)",
286 fn_ty.repr(ccx.tcx()));
288 let function_type; // placeholder so that the memory ownership works out ok
290 let (sig, abi, env) = match fn_ty.sty {
291 ty::ty_bare_fn(_, ref f) => {
292 (&f.sig, f.abi, None)
294 ty::ty_closure(closure_did, substs) => {
295 let typer = common::NormalizingClosureTyper::new(ccx.tcx());
296 function_type = typer.closure_type(closure_did, substs);
297 let self_type = self_type_for_closure(ccx, closure_did, fn_ty);
298 let llenvironment_type = type_of_explicit_arg(ccx, self_type);
299 debug!("decl_rust_fn: function_type={} self_type={}",
300 function_type.repr(ccx.tcx()),
301 self_type.repr(ccx.tcx()));
302 (&function_type.sig, RustCall, Some(llenvironment_type))
304 _ => ccx.sess().bug("expected closure or fn")
307 let sig = ty::erase_late_bound_regions(ccx.tcx(), sig);
308 let sig = ty::Binder(sig);
310 debug!("decl_rust_fn: sig={} (after erasing regions)",
311 sig.repr(ccx.tcx()));
313 let llfty = type_of_rust_fn(ccx, env, &sig, abi);
315 debug!("decl_rust_fn: llfty={}",
316 ccx.tn().type_to_string(llfty));
318 let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, sig.0.output /* (1) */);
319 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
320 attrs.apply_llfn(llfn);
322 // (1) it's ok to directly access sig.0.output because we erased all late-bound-regions above
327 pub fn decl_internal_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
328 fn_ty: Ty<'tcx>, name: &str) -> ValueRef {
329 let llfn = decl_rust_fn(ccx, fn_ty, name);
330 llvm::SetLinkage(llfn, llvm::InternalLinkage);
334 pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
335 t: Ty<'tcx>) -> ValueRef {
336 let name = csearch::get_symbol(&ccx.sess().cstore, did);
337 let ty = type_of(ccx, t);
338 match ccx.externs().borrow_mut().get(&name) {
339 Some(n) => return *n,
343 let buf = CString::new(name.clone()).unwrap();
344 let c = llvm::LLVMAddGlobal(ccx.llmod(), ty.to_ref(), buf.as_ptr());
345 // Thread-local statics in some other crate need to *always* be linked
346 // against in a thread-local fashion, so we need to be sure to apply the
347 // thread-local attribute locally if it was present remotely. If we
348 // don't do this then linker errors can be generated where the linker
349 // complains that one object files has a thread local version of the
350 // symbol and another one doesn't.
351 for attr in &*ty::get_attrs(ccx.tcx(), did) {
352 if attr.check_name("thread_local") {
353 llvm::set_thread_local(c, true);
356 ccx.externs().borrow_mut().insert(name.to_string(), c);
361 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
362 info_ty: Ty<'tcx>, it: LangItem) -> ast::DefId {
363 match bcx.tcx().lang_items.require(it) {
366 bcx.sess().fatal(&format!("allocation of `{}` {}",
367 bcx.ty_to_string(info_ty),
373 // The following malloc_raw_dyn* functions allocate a box to contain
374 // a given type, but with a potentially dynamic size.
376 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
382 -> Result<'blk, 'tcx> {
383 let _icx = push_ctxt("malloc_raw_exchange");
386 let r = callee::trans_lang_call(bcx,
387 require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
392 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
395 // Type descriptor and type glue stuff
397 pub fn get_tydesc<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
398 t: Ty<'tcx>) -> Rc<tydesc_info<'tcx>> {
399 match ccx.tydescs().borrow().get(&t) {
400 Some(inf) => return inf.clone(),
404 ccx.stats().n_static_tydescs.set(ccx.stats().n_static_tydescs.get() + 1);
405 let inf = Rc::new(glue::declare_tydesc(ccx, t));
407 ccx.tydescs().borrow_mut().insert(t, inf.clone());
411 #[allow(dead_code)] // useful
412 pub fn set_optimize_for_size(f: ValueRef) {
413 llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
416 pub fn set_no_inline(f: ValueRef) {
417 llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
420 #[allow(dead_code)] // useful
421 pub fn set_no_unwind(f: ValueRef) {
422 llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
425 // Tell LLVM to emit the information necessary to unwind the stack for the
427 pub fn set_uwtable(f: ValueRef) {
428 llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
431 pub fn set_inline_hint(f: ValueRef) {
432 llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
435 pub fn set_llvm_fn_attrs(ccx: &CrateContext, attrs: &[ast::Attribute], llfn: ValueRef) {
436 use syntax::attr::{find_inline_attr, InlineAttr};
437 // Set the inline hint if there is one
438 match find_inline_attr(Some(ccx.sess().diagnostic()), attrs) {
439 InlineAttr::Hint => set_inline_hint(llfn),
440 InlineAttr::Always => set_always_inline(llfn),
441 InlineAttr::Never => set_no_inline(llfn),
442 InlineAttr::None => { /* fallthrough */ }
447 match &attr.name()[..] {
448 "no_stack_check" => unset_split_stack(llfn),
449 "no_split_stack" => {
450 unset_split_stack(llfn);
451 ccx.sess().span_warn(attr.span,
452 "no_split_stack is a deprecated synonym for no_stack_check");
455 llvm::LLVMAddFunctionAttribute(llfn,
456 llvm::FunctionIndex as c_uint,
457 llvm::ColdAttribute as uint64_t)
462 attr::mark_used(attr);
467 pub fn set_always_inline(f: ValueRef) {
468 llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
471 pub fn set_split_stack(f: ValueRef) {
473 llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint,
474 "split-stack\0".as_ptr() as *const _);
478 pub fn unset_split_stack(f: ValueRef) {
480 llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint,
481 "split-stack\0".as_ptr() as *const _);
485 // Double-check that we never ask LLVM to declare the same symbol twice. It
486 // silently mangles such symbols, breaking our linkage model.
487 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
488 if ccx.all_llvm_symbols().borrow().contains(&sym) {
489 ccx.sess().bug(&format!("duplicate LLVM symbol: {}", sym));
491 ccx.all_llvm_symbols().borrow_mut().insert(sym);
495 pub fn get_res_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
498 parent_id: ast::DefId,
499 substs: &Substs<'tcx>)
501 let _icx = push_ctxt("trans_res_dtor");
502 let did = inline::maybe_instantiate_inline(ccx, did);
504 if !substs.types.is_empty() {
505 assert_eq!(did.krate, ast::LOCAL_CRATE);
507 // Since we're in trans we don't care for any region parameters
508 let substs = ccx.tcx().mk_substs(Substs::erased(substs.types.clone()));
510 let (val, _, _) = monomorphize::monomorphic_fn(ccx, did, substs, None);
513 } else if did.krate == ast::LOCAL_CRATE {
514 get_item_val(ccx, did.node)
517 let name = csearch::get_symbol(&ccx.sess().cstore, did);
518 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
519 let llty = type_of_dtor(ccx, class_ty);
520 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(),
522 &[glue::get_drop_glue_type(ccx, t)],
523 ty::mk_nil(ccx.tcx()));
525 &mut *ccx.externs().borrow_mut(),
533 pub fn bin_op_to_icmp_predicate(ccx: &CrateContext, op: ast::BinOp_, signed: bool)
534 -> llvm::IntPredicate {
536 ast::BiEq => llvm::IntEQ,
537 ast::BiNe => llvm::IntNE,
538 ast::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
539 ast::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
540 ast::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
541 ast::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
543 ccx.sess().bug(&format!("comparison_op_to_icmp_predicate: expected \
544 comparison operator, found {:?}", op));
549 pub fn bin_op_to_fcmp_predicate(ccx: &CrateContext, op: ast::BinOp_)
550 -> llvm::RealPredicate {
552 ast::BiEq => llvm::RealOEQ,
553 ast::BiNe => llvm::RealUNE,
554 ast::BiLt => llvm::RealOLT,
555 ast::BiLe => llvm::RealOLE,
556 ast::BiGt => llvm::RealOGT,
557 ast::BiGe => llvm::RealOGE,
559 ccx.sess().bug(&format!("comparison_op_to_fcmp_predicate: expected \
560 comparison operator, found {:?}", op));
565 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
573 ty::ty_tup(ref tys) if tys.is_empty() => {
574 // We don't need to do actual comparisons for nil.
575 // () == () holds but () < () does not.
577 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(bcx.ccx(), true),
578 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(bcx.ccx(), false),
579 // refinements would be nice
580 _ => bcx.sess().bug("compare_scalar_types: must be a comparison operator")
583 ty::ty_bool | ty::ty_uint(_) | ty::ty_char => {
584 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
586 ty::ty_ptr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
587 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, false), lhs, rhs, debug_loc)
590 ICmp(bcx, bin_op_to_icmp_predicate(bcx.ccx(), op, true), lhs, rhs, debug_loc)
593 FCmp(bcx, bin_op_to_fcmp_predicate(bcx.ccx(), op), lhs, rhs, debug_loc)
595 // Should never get here, because t is scalar.
596 _ => bcx.sess().bug("non-scalar type passed to compare_scalar_types")
600 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
607 let signed = match t.sty {
609 // The comparison operators for floating point vectors are challenging.
610 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
611 // then bitcast to a floating point vector, the result will be `-NaN`
612 // for each truth value. Because of this they are unsupported.
613 bcx.sess().bug("compare_simd_types: comparison operators \
614 not supported for floating point SIMD types")
616 ty::ty_uint(_) => false,
617 ty::ty_int(_) => true,
618 _ => bcx.sess().bug("compare_simd_types: invalid SIMD type"),
621 let cmp = bin_op_to_icmp_predicate(bcx.ccx(), op, signed);
622 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
623 // to get the correctly sized type. This will compile to a single instruction
624 // once the IR is converted to assembly if the SIMD instruction is supported
625 // by the target architecture.
626 SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), val_ty(lhs))
629 // Iterates through the elements of a structural type.
630 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
634 -> Block<'blk, 'tcx> where
635 F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
637 let _icx = push_ctxt("iter_structural_ty");
639 fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
640 repr: &adt::Repr<'tcx>,
642 variant: &ty::VariantInfo<'tcx>,
643 substs: &Substs<'tcx>,
645 -> Block<'blk, 'tcx> where
646 F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>,
648 let _icx = push_ctxt("iter_variant");
652 for (i, &arg) in variant.args.iter().enumerate() {
653 let arg = monomorphize::apply_param_substs(tcx, substs, &arg);
654 cx = f(cx, adt::trans_field_ptr(cx, repr, av, variant.disr_val, i), arg);
659 let (data_ptr, info) = if common::type_is_sized(cx.tcx(), t) {
662 let data = GEPi(cx, av, &[0, abi::FAT_PTR_ADDR]);
663 let info = GEPi(cx, av, &[0, abi::FAT_PTR_EXTRA]);
664 (Load(cx, data), Some(Load(cx, info)))
669 ty::ty_struct(..) => {
670 let repr = adt::represent_type(cx.ccx(), t);
671 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
672 for (i, field_ty) in field_tys.iter().enumerate() {
673 let field_ty = field_ty.mt.ty;
674 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, discr, i);
676 let val = if common::type_is_sized(cx.tcx(), field_ty) {
679 let scratch = datum::rvalue_scratch_datum(cx, field_ty, "__fat_ptr_iter");
680 Store(cx, llfld_a, GEPi(cx, scratch.val, &[0, abi::FAT_PTR_ADDR]));
681 Store(cx, info.unwrap(), GEPi(cx, scratch.val, &[0, abi::FAT_PTR_EXTRA]));
684 cx = f(cx, val, field_ty);
688 ty::ty_closure(def_id, substs) => {
689 let repr = adt::represent_type(cx.ccx(), t);
690 let typer = common::NormalizingClosureTyper::new(cx.tcx());
691 let upvars = typer.closure_upvars(def_id, substs).unwrap();
692 for (i, upvar) in upvars.iter().enumerate() {
693 let llupvar = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
694 cx = f(cx, llupvar, upvar.ty);
697 ty::ty_vec(_, Some(n)) => {
698 let (base, len) = tvec::get_fixed_base_and_len(cx, data_ptr, n);
699 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
700 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
702 ty::ty_tup(ref args) => {
703 let repr = adt::represent_type(cx.ccx(), t);
704 for (i, arg) in args.iter().enumerate() {
705 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
706 cx = f(cx, llfld_a, *arg);
709 ty::ty_enum(tid, substs) => {
713 let repr = adt::represent_type(ccx, t);
714 let variants = ty::enum_variants(ccx.tcx(), tid);
715 let n_variants = (*variants).len();
717 // NB: we must hit the discriminant first so that structural
718 // comparison know not to proceed when the discriminants differ.
720 match adt::trans_switch(cx, &*repr, av) {
721 (_match::Single, None) => {
722 cx = iter_variant(cx, &*repr, av, &*(*variants)[0],
725 (_match::Switch, Some(lldiscrim_a)) => {
726 cx = f(cx, lldiscrim_a, cx.tcx().types.int);
727 let unr_cx = fcx.new_temp_block("enum-iter-unr");
729 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
731 let next_cx = fcx.new_temp_block("enum-iter-next");
733 for variant in &(*variants) {
736 &format!("enum-iter-variant-{}",
737 &variant.disr_val.to_string())
739 match adt::trans_case(cx, &*repr, variant.disr_val) {
740 _match::SingleResult(r) => {
741 AddCase(llswitch, r.val, variant_cx.llbb)
743 _ => ccx.sess().unimpl("value from adt::trans_case \
744 in iter_structural_ty")
747 iter_variant(variant_cx,
753 Br(variant_cx, next_cx.llbb, DebugLoc::None);
757 _ => ccx.sess().unimpl("value from adt::trans_switch \
758 in iter_structural_ty")
762 cx.sess().unimpl(&format!("type in iter_structural_ty: {}",
763 ty_to_string(cx.tcx(), t)))
769 pub fn cast_shift_expr_rhs(cx: Block,
774 cast_shift_rhs(op, lhs, rhs,
775 |a,b| Trunc(cx, a, b),
776 |a,b| ZExt(cx, a, b))
779 pub fn cast_shift_const_rhs(op: ast::BinOp,
780 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
781 cast_shift_rhs(op, lhs, rhs,
782 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
783 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
786 pub fn cast_shift_rhs<F, G>(op: ast::BinOp,
792 F: FnOnce(ValueRef, Type) -> ValueRef,
793 G: FnOnce(ValueRef, Type) -> ValueRef,
795 // Shifts may have any size int on the rhs
796 if ast_util::is_shift_binop(op.node) {
797 let mut rhs_llty = val_ty(rhs);
798 let mut lhs_llty = val_ty(lhs);
799 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
800 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
801 let rhs_sz = rhs_llty.int_width();
802 let lhs_sz = lhs_llty.int_width();
805 } else if lhs_sz > rhs_sz {
806 // FIXME (#1877: If shifting by negative
807 // values becomes not undefined then this is wrong.
817 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
818 cx: Block<'blk, 'tcx>,
819 call_info: NodeIdAndSpan,
824 -> Block<'blk, 'tcx> {
825 let (zero_text, overflow_text) = if divrem.node == ast::BiDiv {
826 ("attempted to divide by zero",
827 "attempted to divide with overflow")
829 ("attempted remainder with a divisor of zero",
830 "attempted remainder with overflow")
832 let debug_loc = call_info.debug_loc();
834 let (is_zero, is_signed) = match rhs_t.sty {
836 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0, false);
837 (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
840 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0, false);
841 (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
844 cx.sess().bug(&format!("fail-if-zero on unexpected type: {}",
845 ty_to_string(cx.tcx(), rhs_t)));
848 let bcx = with_cond(cx, is_zero, |bcx| {
849 controlflow::trans_fail(bcx, call_info, InternedString::new(zero_text))
852 // To quote LLVM's documentation for the sdiv instruction:
854 // Division by zero leads to undefined behavior. Overflow also leads
855 // to undefined behavior; this is a rare case, but can occur, for
856 // example, by doing a 32-bit division of -2147483648 by -1.
858 // In order to avoid undefined behavior, we perform runtime checks for
859 // signed division/remainder which would trigger overflow. For unsigned
860 // integers, no action beyond checking for zero need be taken.
862 let (llty, min) = match rhs_t.sty {
864 let llty = Type::int_from_ty(cx.ccx(), t);
866 ast::TyIs(_) if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
867 ast::TyIs(_) => i64::MIN as u64,
868 ast::TyI8 => i8::MIN as u64,
869 ast::TyI16 => i16::MIN as u64,
870 ast::TyI32 => i32::MIN as u64,
871 ast::TyI64 => i64::MIN as u64,
877 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
878 C_integral(llty, -1, false), debug_loc);
879 with_cond(bcx, minus_one, |bcx| {
880 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
881 C_integral(llty, min, true), debug_loc);
882 with_cond(bcx, is_min, |bcx| {
883 controlflow::trans_fail(bcx,
885 InternedString::new(overflow_text))
893 pub fn trans_external_path<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
894 did: ast::DefId, t: Ty<'tcx>) -> ValueRef {
895 let name = csearch::get_symbol(&ccx.sess().cstore, did);
897 ty::ty_bare_fn(_, ref fn_ty) => {
898 match ccx.sess().target.target.adjust_abi(fn_ty.abi) {
900 get_extern_rust_fn(ccx, t, &name[..], did)
903 ccx.sess().bug("unexpected intrinsic in trans_external_path")
906 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
912 get_extern_const(ccx, did, t)
917 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
922 -> (ValueRef, Block<'blk, 'tcx>) {
923 let _icx = push_ctxt("invoke_");
924 if bcx.unreachable.get() {
925 return (C_null(Type::i8(bcx.ccx())), bcx);
928 let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
930 match bcx.opt_node_id {
932 debug!("invoke at ???");
935 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
939 if need_invoke(bcx) {
940 debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
941 for &llarg in llargs {
942 debug!("arg: {}", bcx.val_to_string(llarg));
944 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
945 let landing_pad = bcx.fcx.get_landing_pad();
947 let llresult = Invoke(bcx,
954 return (llresult, normal_bcx);
956 debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
957 for &llarg in llargs {
958 debug!("arg: {}", bcx.val_to_string(llarg));
961 let llresult = Call(bcx,
966 return (llresult, bcx);
970 pub fn need_invoke(bcx: Block) -> bool {
971 if bcx.sess().no_landing_pads() {
975 // Avoid using invoke if we are already inside a landing pad.
980 bcx.fcx.needs_invoke()
983 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
984 v: ValueRef, t: Ty<'tcx>) -> ValueRef {
985 let _icx = push_ctxt("load_if_immediate");
986 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
990 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
991 /// differs from the type used for SSA values. Also handles various special cases where the type
992 /// gives us better information about what we are loading.
993 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
994 ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
995 if type_is_zero_size(cx.ccx(), t) {
996 C_undef(type_of::type_of(cx.ccx(), t))
997 } else if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
998 // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
999 // for this leads to bad optimizations, so its arg type is an appropriately sized integer
1000 // and we have to convert it
1001 Load(cx, BitCast(cx, ptr, type_of::arg_type_of(cx.ccx(), t).ptr_to()))
1004 let global = llvm::LLVMIsAGlobalVariable(ptr);
1005 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
1006 let val = llvm::LLVMGetInitializer(global);
1008 // This could go into its own function, for DRY.
1009 // (something like "pre-store packing/post-load unpacking")
1010 if ty::type_is_bool(t) {
1011 return Trunc(cx, val, Type::i1(cx.ccx()));
1018 if ty::type_is_bool(t) {
1019 Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
1020 } else if ty::type_is_char(t) {
1021 // a char is a Unicode codepoint, and so takes values from 0
1022 // to 0x10FFFF inclusive only.
1023 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1024 } else if (ty::type_is_region_ptr(t) || ty::type_is_unique(t))
1025 && !common::type_is_fat_ptr(cx.tcx(), t) {
1026 LoadNonNull(cx, ptr)
1033 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
1034 /// differs from the type used for SSA values.
1035 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
1036 if ty::type_is_bool(t) {
1037 Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1038 } else if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
1039 // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
1040 // for this leads to bad optimizations, so its arg type is an appropriately sized integer
1041 // and we have to convert it
1042 Store(cx, v, BitCast(cx, dst, type_of::arg_type_of(cx.ccx(), t).ptr_to()));
1048 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local)
1049 -> Block<'blk, 'tcx> {
1050 debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
1051 let _indenter = indenter();
1052 let _icx = push_ctxt("init_local");
1053 _match::store_local(bcx, local)
1056 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1058 llbb: BasicBlockRef)
1059 -> Block<'blk, 'tcx> {
1060 common::BlockS::new(llbb, is_lpad, None, fcx)
1063 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
1066 -> Block<'blk, 'tcx> where
1067 F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>,
1069 let _icx = push_ctxt("with_cond");
1071 if bcx.unreachable.get() ||
1072 (common::is_const(val) && common::const_to_uint(val) == 0) {
1077 let next_cx = fcx.new_temp_block("next");
1078 let cond_cx = fcx.new_temp_block("cond");
1079 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
1080 let after_cx = f(cond_cx);
1081 if !after_cx.terminated.get() {
1082 Br(after_cx, next_cx.llbb, DebugLoc::None);
1087 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
1088 if cx.sess().opts.optimize == config::No {
1092 let _icx = push_ctxt("lifetime_start");
1095 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
1096 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1097 let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
1098 Call(cx, lifetime_start, &[llsize, ptr], None, DebugLoc::None);
1101 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
1102 if cx.sess().opts.optimize == config::No {
1106 let _icx = push_ctxt("lifetime_end");
1109 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
1110 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1111 let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
1112 Call(cx, lifetime_end, &[llsize, ptr], None, DebugLoc::None);
1115 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1116 let _icx = push_ctxt("call_memcpy");
1118 let key = match &ccx.sess().target.target.target_pointer_width[..] {
1119 "32" => "llvm.memcpy.p0i8.p0i8.i32",
1120 "64" => "llvm.memcpy.p0i8.p0i8.i64",
1121 tws => panic!("Unsupported target word size for memcpy: {}", tws),
1123 let memcpy = ccx.get_intrinsic(&key);
1124 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1125 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1126 let size = IntCast(cx, n_bytes, ccx.int_type());
1127 let align = C_i32(ccx, align as i32);
1128 let volatile = C_bool(ccx, false);
1129 Call(cx, memcpy, &[dst_ptr, src_ptr, size, align, volatile], None, DebugLoc::None);
1132 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1133 dst: ValueRef, src: ValueRef,
1135 let _icx = push_ctxt("memcpy_ty");
1136 let ccx = bcx.ccx();
1137 if ty::type_is_structural(t) {
1138 let llty = type_of::type_of(ccx, t);
1139 let llsz = llsize_of(ccx, llty);
1140 let llalign = type_of::align_of(ccx, t);
1141 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1143 store_ty(bcx, load_ty(bcx, src, t), dst, t);
1147 pub fn zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1148 if cx.unreachable.get() { return; }
1149 let _icx = push_ctxt("zero_mem");
1151 memzero(&B(bcx), llptr, t);
1154 // Always use this function instead of storing a zero constant to the memory
1155 // in question. If you store a zero constant, LLVM will drown in vreg
1156 // allocation for large data structures, and the generated code will be
1157 // awful. (A telltale sign of this is large quantities of
1158 // `mov [byte ptr foo],0` in the generated code.)
1159 fn memzero<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>) {
1160 let _icx = push_ctxt("memzero");
1163 let llty = type_of::type_of(ccx, ty);
1165 let intrinsic_key = match &ccx.sess().target.target.target_pointer_width[..] {
1166 "32" => "llvm.memset.p0i8.i32",
1167 "64" => "llvm.memset.p0i8.i64",
1168 tws => panic!("Unsupported target word size for memset: {}", tws),
1171 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1172 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1173 let llzeroval = C_u8(ccx, 0);
1174 let size = machine::llsize_of(ccx, llty);
1175 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
1176 let volatile = C_bool(ccx, false);
1177 b.call(llintrinsicfn, &[llptr, llzeroval, size, align, volatile], None);
1180 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, name: &str) -> ValueRef {
1181 let _icx = push_ctxt("alloc_ty");
1182 let ccx = bcx.ccx();
1183 let ty = type_of::type_of(ccx, t);
1184 assert!(!ty::type_has_params(t));
1185 let val = alloca(bcx, ty, name);
1189 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
1190 let p = alloca_no_lifetime(cx, ty, name);
1191 call_lifetime_start(cx, p);
1195 pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
1196 let _icx = push_ctxt("alloca");
1197 if cx.unreachable.get() {
1199 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1202 debuginfo::clear_source_location(cx.fcx);
1203 Alloca(cx, ty, name)
1206 // Creates the alloca slot which holds the pointer to the slot for the final return value
1207 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1208 output_type: Ty<'tcx>) -> ValueRef {
1209 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1211 // We create an alloca to hold a pointer of type `output_type`
1212 // which will hold the pointer to the right alloca which has the
1214 if fcx.needs_ret_allocas {
1215 // Let's create the stack slot
1216 let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1218 // and if we're using an out pointer, then store that in our newly made slot
1219 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1220 let outptr = get_param(fcx.llfn, 0);
1222 let b = fcx.ccx.builder();
1223 b.position_before(fcx.alloca_insert_pt.get().unwrap());
1224 b.store(outptr, slot);
1229 // But if there are no nested returns, we skip the indirection and have a single
1232 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1233 get_param(fcx.llfn, 0)
1235 AllocaFcx(fcx, lloutputtype, "sret_slot")
1240 struct FindNestedReturn {
1244 impl FindNestedReturn {
1245 fn new() -> FindNestedReturn {
1246 FindNestedReturn { found: false }
1250 impl<'v> Visitor<'v> for FindNestedReturn {
1251 fn visit_expr(&mut self, e: &ast::Expr) {
1253 ast::ExprRet(..) => {
1256 _ => visit::walk_expr(self, e)
1261 fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>) {
1262 let blk = match tcx.map.find(id) {
1263 Some(ast_map::NodeItem(i)) => {
1265 ast::ItemFn(_, _, _, _, ref blk) => {
1268 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1271 Some(ast_map::NodeTraitItem(trait_method)) => {
1272 match *trait_method {
1273 ast::ProvidedMethod(ref m) => {
1275 ast::MethDecl(_, _, _, _, _, _, ref blk, _) => {
1278 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1281 ast::RequiredMethod(_) => {
1282 tcx.sess.bug("unexpected variant: required trait method \
1283 in has_nested_returns")
1285 ast::TypeTraitItem(_) => {
1286 tcx.sess.bug("unexpected variant: type trait item in \
1287 has_nested_returns")
1291 Some(ast_map::NodeImplItem(ii)) => {
1293 ast::MethodImplItem(ref m) => {
1295 ast::MethDecl(_, _, _, _, _, _, ref blk, _) => {
1298 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1301 ast::TypeImplItem(_) => {
1302 tcx.sess.bug("unexpected variant: type impl item in \
1303 has_nested_returns")
1307 Some(ast_map::NodeExpr(e)) => {
1309 ast::ExprClosure(_, _, ref blk) => {
1312 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1315 Some(ast_map::NodeVariant(..)) |
1316 Some(ast_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1319 None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1321 _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
1322 tcx.map.path_to_string(id)))
1325 (blk.id, Some(cfg::CFG::new(tcx, &**blk)))
1328 // Checks for the presence of "nested returns" in a function.
1329 // Nested returns are when the inner expression of a return expression
1330 // (the 'expr' in 'return expr') contains a return expression. Only cases
1331 // where the outer return is actually reachable are considered. Implicit
1332 // returns from the end of blocks are considered as well.
1334 // This check is needed to handle the case where the inner expression is
1335 // part of a larger expression that may have already partially-filled the
1336 // return slot alloca. This can cause errors related to clean-up due to
1337 // the clobbering of the existing value in the return slot.
1338 fn has_nested_returns(tcx: &ty::ctxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1339 for n in cfg.graph.depth_traverse(cfg.entry) {
1340 match tcx.map.find(n.id()) {
1341 Some(ast_map::NodeExpr(ex)) => {
1342 if let ast::ExprRet(Some(ref ret_expr)) = ex.node {
1343 let mut visitor = FindNestedReturn::new();
1344 visit::walk_expr(&mut visitor, &**ret_expr);
1350 Some(ast_map::NodeBlock(blk)) if blk.id == blk_id => {
1351 let mut visitor = FindNestedReturn::new();
1352 visit::walk_expr_opt(&mut visitor, &blk.expr);
1364 // NB: must keep 4 fns in sync:
1367 // - create_datums_for_fn_args.
1371 // Be warned! You must call `init_function` before doing anything with the
1372 // returned function context.
1373 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1377 output_type: ty::FnOutput<'tcx>,
1378 param_substs: &'tcx Substs<'tcx>,
1380 block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1381 -> FunctionContext<'a, 'tcx> {
1382 common::validate_substs(param_substs);
1384 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1388 ccx.tcx().map.path_to_string(id).to_string()
1390 id, param_substs.repr(ccx.tcx()));
1392 let uses_outptr = match output_type {
1393 ty::FnConverging(output_type) => {
1394 let substd_output_type =
1395 monomorphize::apply_param_substs(ccx.tcx(), param_substs, &output_type);
1396 type_of::return_uses_outptr(ccx, substd_output_type)
1398 ty::FnDiverging => false
1400 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1401 let (blk_id, cfg) = build_cfg(ccx.tcx(), id);
1402 let nested_returns = if let Some(ref cfg) = cfg {
1403 has_nested_returns(ccx.tcx(), cfg, blk_id)
1408 let mut fcx = FunctionContext {
1411 llretslotptr: Cell::new(None),
1412 param_env: ty::empty_parameter_environment(ccx.tcx()),
1413 alloca_insert_pt: Cell::new(None),
1414 llreturn: Cell::new(None),
1415 needs_ret_allocas: nested_returns,
1416 personality: Cell::new(None),
1417 caller_expects_out_pointer: uses_outptr,
1418 lllocals: RefCell::new(NodeMap()),
1419 llupvars: RefCell::new(NodeMap()),
1421 param_substs: param_substs,
1423 block_arena: block_arena,
1425 debug_context: debug_context,
1426 scopes: RefCell::new(Vec::new()),
1431 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1437 /// Performs setup on a newly created function, creating the entry scope block
1438 /// and allocating space for the return pointer.
1439 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1441 output: ty::FnOutput<'tcx>)
1442 -> Block<'a, 'tcx> {
1443 let entry_bcx = fcx.new_temp_block("entry-block");
1445 // Use a dummy instruction as the insertion point for all allocas.
1446 // This is later removed in FunctionContext::cleanup.
1447 fcx.alloca_insert_pt.set(Some(unsafe {
1448 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1449 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1452 if let ty::FnConverging(output_type) = output {
1453 // This shouldn't need to recompute the return type,
1454 // as new_fn_ctxt did it already.
1455 let substd_output_type = fcx.monomorphize(&output_type);
1456 if !return_type_is_void(fcx.ccx, substd_output_type) {
1457 // If the function returns nil/bot, there is no real return
1458 // value, so do not set `llretslotptr`.
1459 if !skip_retptr || fcx.caller_expects_out_pointer {
1460 // Otherwise, we normally allocate the llretslotptr, unless we
1461 // have been instructed to skip it for immediate return
1463 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1471 // NB: must keep 4 fns in sync:
1474 // - create_datums_for_fn_args.
1478 pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>)
1480 use trans::datum::{ByRef, ByValue};
1483 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1487 // work around bizarre resolve errors
1488 type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
1490 // create_datums_for_fn_args: creates rvalue datums for each of the
1491 // incoming function arguments. These will later be stored into
1492 // appropriate lvalue datums.
1493 pub fn create_datums_for_fn_args<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1494 arg_tys: &[Ty<'tcx>])
1495 -> Vec<RvalueDatum<'tcx>> {
1496 let _icx = push_ctxt("create_datums_for_fn_args");
1498 // Return an array wrapping the ValueRefs that we get from `get_param` for
1499 // each argument into datums.
1500 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1501 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1502 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1506 /// Creates rvalue datums for each of the incoming function arguments and
1507 /// tuples the arguments. These will later be stored into appropriate lvalue
1510 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1511 fn create_datums_for_fn_args_under_call_abi<'blk, 'tcx>(
1512 mut bcx: Block<'blk, 'tcx>,
1513 arg_scope: cleanup::CustomScopeIndex,
1514 arg_tys: &[Ty<'tcx>])
1515 -> Vec<RvalueDatum<'tcx>> {
1516 let mut result = Vec::new();
1517 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1518 if i < arg_tys.len() - 1 {
1519 // Regular argument.
1520 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1521 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1526 // This is the last argument. Tuple it.
1528 ty::ty_tup(ref tupled_arg_tys) => {
1529 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1532 datum::lvalue_scratch_datum(bcx,
1535 tuple_args_scope_id,
1540 for (j, &tupled_arg_ty) in
1541 tupled_arg_tys.iter().enumerate() {
1543 get_param(bcx.fcx.llfn,
1544 bcx.fcx.arg_pos(i + j) as c_uint);
1545 let lldest = GEPi(bcx, llval, &[0, j]);
1546 let datum = datum::Datum::new(
1549 arg_kind(bcx.fcx, tupled_arg_ty));
1550 bcx = datum.store_to(bcx, lldest);
1554 let tuple = unpack_datum!(bcx,
1555 tuple.to_expr_datum()
1556 .to_rvalue_datum(bcx,
1561 bcx.tcx().sess.bug("last argument of a function with \
1562 `rust-call` ABI isn't a tuple?!")
1571 fn copy_args_to_allocas<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1572 arg_scope: cleanup::CustomScopeIndex,
1574 arg_datums: Vec<RvalueDatum<'tcx>>)
1575 -> Block<'blk, 'tcx> {
1576 debug!("copy_args_to_allocas");
1578 let _icx = push_ctxt("copy_args_to_allocas");
1581 let arg_scope_id = cleanup::CustomScope(arg_scope);
1583 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
1584 // For certain mode/type combinations, the raw llarg values are passed
1585 // by value. However, within the fn body itself, we want to always
1586 // have all locals and arguments be by-ref so that we can cancel the
1587 // cleanup and for better interaction with LLVM's debug info. So, if
1588 // the argument would be passed by value, we store it into an alloca.
1589 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1590 // the event it's not truly needed.
1592 bcx = _match::store_arg(bcx, &*args[i].pat, arg_datum, arg_scope_id);
1593 debuginfo::create_argument_metadata(bcx, &args[i]);
1599 fn copy_closure_args_to_allocas<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1600 arg_scope: cleanup::CustomScopeIndex,
1602 arg_datums: Vec<RvalueDatum<'tcx>>,
1603 monomorphized_arg_types: &[Ty<'tcx>])
1604 -> Block<'blk, 'tcx> {
1605 let _icx = push_ctxt("copy_closure_args_to_allocas");
1606 let arg_scope_id = cleanup::CustomScope(arg_scope);
1608 assert_eq!(arg_datums.len(), 1);
1610 let arg_datum = arg_datums.into_iter().next().unwrap();
1612 // Untuple the rest of the arguments.
1615 arg_datum.to_lvalue_datum_in_scope(bcx,
1618 let untupled_arg_types = match monomorphized_arg_types[0].sty {
1619 ty::ty_tup(ref types) => &types[..],
1621 bcx.tcx().sess.span_bug(args[0].pat.span,
1622 "first arg to `rust-call` ABI function \
1626 for j in 0..args.len() {
1627 let tuple_element_type = untupled_arg_types[j];
1628 let tuple_element_datum =
1629 tuple_datum.get_element(bcx,
1631 |llval| GEPi(bcx, llval, &[0, j]));
1632 let tuple_element_datum = tuple_element_datum.to_expr_datum();
1633 let tuple_element_datum =
1635 tuple_element_datum.to_rvalue_datum(bcx,
1637 bcx = _match::store_arg(bcx,
1639 tuple_element_datum,
1642 debuginfo::create_argument_metadata(bcx, &args[j]);
1648 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1649 // and builds the return block.
1650 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1651 last_bcx: Block<'blk, 'tcx>,
1652 retty: ty::FnOutput<'tcx>,
1653 ret_debug_loc: DebugLoc) {
1654 let _icx = push_ctxt("finish_fn");
1656 let ret_cx = match fcx.llreturn.get() {
1658 if !last_bcx.terminated.get() {
1659 Br(last_bcx, llreturn, DebugLoc::None);
1661 raw_block(fcx, false, llreturn)
1666 // This shouldn't need to recompute the return type,
1667 // as new_fn_ctxt did it already.
1668 let substd_retty = fcx.monomorphize(&retty);
1669 build_return_block(fcx, ret_cx, substd_retty, ret_debug_loc);
1671 debuginfo::clear_source_location(fcx);
1675 // Builds the return block for a function.
1676 pub fn build_return_block<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1677 ret_cx: Block<'blk, 'tcx>,
1678 retty: ty::FnOutput<'tcx>,
1679 ret_debug_location: DebugLoc) {
1680 if fcx.llretslotptr.get().is_none() ||
1681 (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1682 return RetVoid(ret_cx, ret_debug_location);
1685 let retslot = if fcx.needs_ret_allocas {
1686 Load(ret_cx, fcx.llretslotptr.get().unwrap())
1688 fcx.llretslotptr.get().unwrap()
1690 let retptr = Value(retslot);
1691 match retptr.get_dominating_store(ret_cx) {
1692 // If there's only a single store to the ret slot, we can directly return
1693 // the value that was stored and omit the store and the alloca
1695 let retval = s.get_operand(0).unwrap().get();
1696 s.erase_from_parent();
1698 if retptr.has_no_uses() {
1699 retptr.erase_from_parent();
1702 let retval = if retty == ty::FnConverging(fcx.ccx.tcx().types.bool) {
1703 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1708 if fcx.caller_expects_out_pointer {
1709 if let ty::FnConverging(retty) = retty {
1710 store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1712 RetVoid(ret_cx, ret_debug_location)
1714 Ret(ret_cx, retval, ret_debug_location)
1717 // Otherwise, copy the return value to the ret slot
1718 None => match retty {
1719 ty::FnConverging(retty) => {
1720 if fcx.caller_expects_out_pointer {
1721 memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1722 RetVoid(ret_cx, ret_debug_location)
1724 Ret(ret_cx, load_ty(ret_cx, retslot, retty), ret_debug_location)
1727 ty::FnDiverging => {
1728 if fcx.caller_expects_out_pointer {
1729 RetVoid(ret_cx, ret_debug_location)
1731 Ret(ret_cx, C_undef(Type::nil(fcx.ccx)), ret_debug_location)
1738 // trans_closure: Builds an LLVM function out of a source function.
1739 // If the function closes over its environment a closure will be
1741 pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1745 param_substs: &'tcx Substs<'tcx>,
1746 fn_ast_id: ast::NodeId,
1747 _attributes: &[ast::Attribute],
1748 output_type: ty::FnOutput<'tcx>,
1750 closure_env: closure::ClosureEnv<'b>) {
1751 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1753 let _icx = push_ctxt("trans_closure");
1754 set_uwtable(llfndecl);
1756 debug!("trans_closure(..., param_substs={})",
1757 param_substs.repr(ccx.tcx()));
1759 let has_env = match closure_env {
1760 closure::ClosureEnv::Closure(_) => true,
1761 closure::ClosureEnv::NotClosure => false,
1764 let (arena, fcx): (TypedArena<_>, FunctionContext);
1765 arena = TypedArena::new();
1766 fcx = new_fn_ctxt(ccx,
1774 let mut bcx = init_function(&fcx, false, output_type);
1776 // cleanup scope for the incoming arguments
1777 let fn_cleanup_debug_loc =
1778 debuginfo::get_cleanup_debug_loc_for_ast_node(ccx, fn_ast_id, body.span, true);
1779 let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1781 let block_ty = node_id_type(bcx, body.id);
1783 // Set up arguments to the function.
1784 let monomorphized_arg_types =
1786 .map(|arg| node_id_type(bcx, arg.id))
1787 .collect::<Vec<_>>();
1788 let monomorphized_arg_types = match closure_env {
1789 closure::ClosureEnv::NotClosure => {
1790 monomorphized_arg_types
1793 // Tuple up closure argument types for the "rust-call" ABI.
1794 closure::ClosureEnv::Closure(_) => {
1795 vec![ty::mk_tup(ccx.tcx(), monomorphized_arg_types)]
1798 for monomorphized_arg_type in &monomorphized_arg_types {
1799 debug!("trans_closure: monomorphized_arg_type: {}",
1800 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1802 debug!("trans_closure: function lltype: {}",
1803 bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1805 let arg_datums = if abi != RustCall {
1806 create_datums_for_fn_args(&fcx,
1807 &monomorphized_arg_types[..])
1809 create_datums_for_fn_args_under_call_abi(
1812 &monomorphized_arg_types[..])
1815 bcx = match closure_env {
1816 closure::ClosureEnv::NotClosure => {
1817 copy_args_to_allocas(bcx,
1822 closure::ClosureEnv::Closure(_) => {
1823 copy_closure_args_to_allocas(
1828 &monomorphized_arg_types[..])
1832 bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
1834 // Up until here, IR instructions for this function have explicitly not been annotated with
1835 // source code location, so we don't step into call setup code. From here on, source location
1836 // emitting should be enabled.
1837 debuginfo::start_emitting_source_locations(&fcx);
1839 let dest = match fcx.llretslotptr.get() {
1840 Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(block_ty), "iret_slot")),
1842 assert!(type_is_zero_size(bcx.ccx(), block_ty));
1847 // This call to trans_block is the place where we bridge between
1848 // translation calls that don't have a return value (trans_crate,
1849 // trans_mod, trans_item, et cetera) and those that do
1850 // (trans_block, trans_expr, et cetera).
1851 bcx = controlflow::trans_block(bcx, body, dest);
1854 expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1855 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1860 match fcx.llreturn.get() {
1862 Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1863 fcx.pop_custom_cleanup_scope(arg_scope);
1866 // Microoptimization writ large: avoid creating a separate
1867 // llreturn basic block
1868 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1872 // Put return block after all other blocks.
1873 // This somewhat improves single-stepping experience in debugger.
1875 let llreturn = fcx.llreturn.get();
1876 if let Some(llreturn) = llreturn {
1877 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1881 let ret_debug_loc = DebugLoc::At(fn_cleanup_debug_loc.id,
1882 fn_cleanup_debug_loc.span);
1884 // Insert the mandatory first few basic blocks before lltop.
1885 finish_fn(&fcx, bcx, output_type, ret_debug_loc);
1888 // trans_fn: creates an LLVM function corresponding to a source language
1890 pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1894 param_substs: &'tcx Substs<'tcx>,
1896 attrs: &[ast::Attribute]) {
1897 let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1898 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1899 let _icx = push_ctxt("trans_fn");
1900 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1901 let output_type = ty::erase_late_bound_regions(ccx.tcx(), &ty::ty_fn_ret(fn_ty));
1902 let abi = ty::ty_fn_abi(fn_ty);
1912 closure::ClosureEnv::NotClosure);
1915 pub fn trans_enum_variant<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1916 _enum_id: ast::NodeId,
1917 variant: &ast::Variant,
1918 _args: &[ast::VariantArg],
1920 param_substs: &'tcx Substs<'tcx>,
1921 llfndecl: ValueRef) {
1922 let _icx = push_ctxt("trans_enum_variant");
1924 trans_enum_variant_or_tuple_like_struct(
1932 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1935 args: callee::CallArgs,
1937 debug_loc: DebugLoc)
1938 -> Result<'blk, 'tcx> {
1940 let ccx = bcx.fcx.ccx;
1941 let tcx = ccx.tcx();
1943 let result_ty = match ctor_ty.sty {
1944 ty::ty_bare_fn(_, ref bft) => {
1945 ty::erase_late_bound_regions(bcx.tcx(), &bft.sig.output()).unwrap()
1947 _ => ccx.sess().bug(
1948 &format!("trans_enum_variant_constructor: \
1949 unexpected ctor return type {}",
1953 // Get location to store the result. If the user does not care about
1954 // the result, just make a stack slot
1955 let llresult = match dest {
1956 expr::SaveIn(d) => d,
1958 if !type_is_zero_size(ccx, result_ty) {
1959 alloc_ty(bcx, result_ty, "constructor_result")
1961 C_undef(type_of::type_of(ccx, result_ty))
1966 if !type_is_zero_size(ccx, result_ty) {
1968 callee::ArgExprs(exprs) => {
1969 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
1970 bcx = expr::trans_adt(bcx,
1975 expr::SaveIn(llresult),
1978 _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
1982 // If the caller doesn't care about the result
1983 // drop the temporary we made
1984 let bcx = match dest {
1985 expr::SaveIn(_) => bcx,
1987 let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
1988 if !type_is_zero_size(ccx, result_ty) {
1989 call_lifetime_end(bcx, llresult);
1995 Result::new(bcx, llresult)
1998 pub fn trans_tuple_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1999 _fields: &[ast::StructField],
2000 ctor_id: ast::NodeId,
2001 param_substs: &'tcx Substs<'tcx>,
2002 llfndecl: ValueRef) {
2003 let _icx = push_ctxt("trans_tuple_struct");
2005 trans_enum_variant_or_tuple_like_struct(
2013 fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2014 ctor_id: ast::NodeId,
2016 param_substs: &'tcx Substs<'tcx>,
2017 llfndecl: ValueRef) {
2018 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2019 let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
2021 let result_ty = match ctor_ty.sty {
2022 ty::ty_bare_fn(_, ref bft) => {
2023 ty::erase_late_bound_regions(ccx.tcx(), &bft.sig.output())
2025 _ => ccx.sess().bug(
2026 &format!("trans_enum_variant_or_tuple_like_struct: \
2027 unexpected ctor return type {}",
2028 ty_to_string(ccx.tcx(), ctor_ty)))
2031 let (arena, fcx): (TypedArena<_>, FunctionContext);
2032 arena = TypedArena::new();
2033 fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
2034 param_substs, None, &arena);
2035 let bcx = init_function(&fcx, false, result_ty);
2037 assert!(!fcx.needs_ret_allocas);
2040 ty::erase_late_bound_regions(
2041 ccx.tcx(), &ty::ty_fn_args(ctor_ty));
2043 let arg_datums = create_datums_for_fn_args(&fcx, &arg_tys[..]);
2045 if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) {
2046 let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
2047 let repr = adt::represent_type(ccx, result_ty.unwrap());
2048 for (i, arg_datum) in arg_datums.into_iter().enumerate() {
2049 let lldestptr = adt::trans_field_ptr(bcx,
2054 arg_datum.store_to(bcx, lldestptr);
2056 adt::trans_set_discr(bcx, &*repr, dest, disr);
2059 finish_fn(&fcx, bcx, result_ty, DebugLoc::None);
2062 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
2063 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
2065 let print_info = ccx.sess().print_enum_sizes();
2067 let levels = ccx.tcx().node_lint_levels.borrow();
2068 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCES);
2069 let lvlsrc = levels.get(&(id, lint_id));
2070 let is_allow = lvlsrc.map_or(true, |&(lvl, _)| lvl == lint::Allow);
2072 if is_allow && !print_info {
2073 // we're not interested in anything here
2077 let ty = ty::node_id_to_type(ccx.tcx(), id);
2078 let avar = adt::represent_type(ccx, ty);
2080 adt::General(_, ref variants, _) => {
2081 for var in variants {
2083 for field in var.fields.iter().skip(1) {
2084 // skip the discriminant
2085 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
2090 _ => { /* its size is either constant or unimportant */ }
2093 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
2094 |(l, s, li), (idx, &size)|
2097 } else if size > s {
2105 let llty = type_of::sizing_type_of(ccx, ty);
2107 let sess = &ccx.tcx().sess;
2108 sess.span_note(sp, &*format!("total size: {} bytes", llsize_of_real(ccx, llty)));
2110 adt::General(..) => {
2111 for (i, var) in enum_def.variants.iter().enumerate() {
2112 ccx.tcx().sess.span_note(var.span,
2113 &*format!("variant data: {} bytes", sizes[i]));
2120 // we only warn if the largest variant is at least thrice as large as
2121 // the second-largest.
2122 if !is_allow && largest > slargest * 3 && slargest > 0 {
2123 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
2124 // pass for the latter already ran.
2125 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCES,
2126 *lvlsrc.unwrap(), Some(sp),
2127 &format!("enum variant is more than three times larger \
2128 ({} bytes) than the next largest (ignoring padding)",
2131 ccx.sess().span_note(enum_def.variants[largest_index].span,
2132 "this variant is the largest");
2136 pub struct TransItemVisitor<'a, 'tcx: 'a> {
2137 pub ccx: &'a CrateContext<'a, 'tcx>,
2140 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
2141 fn visit_item(&mut self, i: &ast::Item) {
2142 trans_item(self.ccx, i);
2146 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
2147 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2148 // applicable to variable declarations and may not really make sense for
2149 // Rust code in the first place but whitelist them anyway and trust that
2150 // the user knows what s/he's doing. Who knows, unanticipated use cases
2151 // may pop up in the future.
2153 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2154 // and don't have to be, LLVM treats them as no-ops.
2156 "appending" => Some(llvm::AppendingLinkage),
2157 "available_externally" => Some(llvm::AvailableExternallyLinkage),
2158 "common" => Some(llvm::CommonLinkage),
2159 "extern_weak" => Some(llvm::ExternalWeakLinkage),
2160 "external" => Some(llvm::ExternalLinkage),
2161 "internal" => Some(llvm::InternalLinkage),
2162 "linkonce" => Some(llvm::LinkOnceAnyLinkage),
2163 "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
2164 "private" => Some(llvm::PrivateLinkage),
2165 "weak" => Some(llvm::WeakAnyLinkage),
2166 "weak_odr" => Some(llvm::WeakODRLinkage),
2172 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
2174 pub enum ValueOrigin {
2175 /// The LLVM `Value` is in this context because the corresponding item was
2176 /// assigned to the current compilation unit.
2177 OriginalTranslation,
2178 /// The `Value`'s corresponding item was assigned to some other compilation
2179 /// unit, but the `Value` was translated in this context anyway because the
2180 /// item is marked `#[inline]`.
2184 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
2185 /// If the `llval` is the direct translation of a specific Rust item, `id`
2186 /// should be set to the `NodeId` of that item. (This mapping should be
2187 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
2188 /// `None`.) `llval_origin` indicates whether `llval` is the translation of an
2189 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
2190 /// assigned to a different compilation unit.
2191 pub fn update_linkage(ccx: &CrateContext,
2193 id: Option<ast::NodeId>,
2194 llval_origin: ValueOrigin) {
2195 match llval_origin {
2197 // `llval` is a translation of an item defined in a separate
2198 // compilation unit. This only makes sense if there are at least
2199 // two compilation units.
2200 assert!(ccx.sess().opts.cg.codegen_units > 1);
2201 // `llval` is a copy of something defined elsewhere, so use
2202 // `AvailableExternallyLinkage` to avoid duplicating code in the
2204 llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
2207 OriginalTranslation => {},
2210 if let Some(id) = id {
2211 let item = ccx.tcx().map.get(id);
2212 if let ast_map::NodeItem(i) = item {
2213 if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
2214 if let Some(linkage) = llvm_linkage_by_name(&name) {
2215 llvm::SetLinkage(llval, linkage);
2217 ccx.sess().span_fatal(i.span, "invalid linkage specified");
2225 Some(id) if ccx.reachable().contains(&id) => {
2226 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2229 // `id` does not refer to an item in `ccx.reachable`.
2230 if ccx.sess().opts.cg.codegen_units > 1 {
2231 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2233 llvm::SetLinkage(llval, llvm::InternalLinkage);
2239 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
2240 let _icx = push_ctxt("trans_item");
2242 let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2245 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
2246 if !generics.is_type_parameterized() {
2247 let trans_everywhere = attr::requests_inline(&item.attrs);
2248 // Ignore `trans_everywhere` for cross-crate inlined items
2249 // (`from_external`). `trans_item` will be called once for each
2250 // compilation unit that references the item, so it will still get
2251 // translated everywhere it's needed.
2252 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2253 let llfn = get_item_val(ccx, item.id);
2254 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2256 foreign::trans_rust_fn_with_foreign_abi(ccx,
2276 if is_origin { OriginalTranslation } else { InlinedCopy });
2280 // Be sure to travel more than just one layer deep to catch nested
2281 // items in blocks and such.
2282 let mut v = TransItemVisitor{ ccx: ccx };
2283 v.visit_block(&**body);
2285 ast::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
2286 meth::trans_impl(ccx,
2292 ast::ItemMod(ref m) => {
2293 trans_mod(&ccx.rotate(), m);
2295 ast::ItemEnum(ref enum_definition, ref gens) => {
2296 if gens.ty_params.is_empty() {
2297 // sizes only make sense for non-generic types
2299 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2302 ast::ItemConst(_, ref expr) => {
2303 // Recurse on the expression to catch items in blocks
2304 let mut v = TransItemVisitor{ ccx: ccx };
2305 v.visit_expr(&**expr);
2307 ast::ItemStatic(_, m, ref expr) => {
2308 // Recurse on the expression to catch items in blocks
2309 let mut v = TransItemVisitor{ ccx: ccx };
2310 v.visit_expr(&**expr);
2312 consts::trans_static(ccx, m, item.id);
2313 let g = get_item_val(ccx, item.id);
2314 update_linkage(ccx, g, Some(item.id), OriginalTranslation);
2316 // Do static_assert checking. It can't really be done much earlier
2317 // because we need to get the value of the bool out of LLVM
2318 if attr::contains_name(&item.attrs, "static_assert") {
2319 if !ty::type_is_bool(ty::expr_ty(ccx.tcx(), expr)) {
2320 ccx.sess().span_fatal(expr.span,
2321 "can only have static_assert on a static \
2324 if m == ast::MutMutable {
2325 ccx.sess().span_fatal(expr.span,
2326 "cannot have static_assert on a mutable \
2330 let v = ccx.static_values().borrow()[item.id].clone();
2332 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2333 ccx.sess().span_fatal(expr.span, "static assertion failed");
2338 ast::ItemForeignMod(ref foreign_mod) => {
2339 foreign::trans_foreign_mod(ccx, foreign_mod);
2341 ast::ItemTrait(..) => {
2342 // Inside of this trait definition, we won't be actually translating any
2343 // functions, but the trait still needs to be walked. Otherwise default
2344 // methods with items will not get translated and will cause ICE's when
2345 // metadata time comes around.
2346 let mut v = TransItemVisitor{ ccx: ccx };
2347 visit::walk_item(&mut v, item);
2349 _ => {/* fall through */ }
2353 // Translate a module. Doing this amounts to translating the items in the
2354 // module; there ends up being no artifact (aside from linkage names) of
2355 // separate modules in the compiled program. That's because modules exist
2356 // only as a convenience for humans working with the code, to organize names
2357 // and control visibility.
2358 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2359 let _icx = push_ctxt("trans_mod");
2360 for item in &m.items {
2361 trans_item(ccx, &**item);
2365 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
2367 ccx.item_symbols().borrow_mut().insert(node_id, sym);
2369 // The stack exhaustion lang item shouldn't have a split stack because
2370 // otherwise it would continue to be exhausted (bad), and both it and the
2371 // eh_personality functions need to be externally linkable.
2372 let def = ast_util::local_def(node_id);
2373 if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2374 unset_split_stack(llfn);
2375 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2377 if ccx.tcx().lang_items.eh_personality() == Some(def) {
2378 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2382 if is_entry_fn(ccx.sess(), node_id) {
2383 // check for the #[rustc_error] annotation, which forces an
2384 // error in trans. This is used to write compile-fail tests
2385 // that actually test that compilation succeeds without
2386 // reporting an error.
2387 if ty::has_attr(ccx.tcx(), local_def(node_id), "rustc_error") {
2388 ccx.tcx().sess.span_fatal(sp, "compilation successful");
2391 create_entry_wrapper(ccx, sp, llfn);
2395 fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2398 node_id: ast::NodeId,
2399 node_type: Ty<'tcx>)
2401 if let ty::ty_bare_fn(_, ref f) = node_type.sty {
2402 if f.abi != Rust && f.abi != RustCall {
2403 ccx.sess().span_bug(sp, &format!("only the `{}` or `{}` calling conventions are valid \
2404 for this function; `{}` was specified",
2405 Rust.name(), RustCall.name(), f.abi.name()));
2408 ccx.sess().span_bug(sp, "expected bare rust function")
2411 let llfn = decl_rust_fn(ccx, node_type, &sym[..]);
2412 finish_register_fn(ccx, sp, sym, node_id, llfn);
2416 pub fn get_fn_llvm_attributes<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_ty: Ty<'tcx>)
2417 -> llvm::AttrBuilder
2419 use middle::ty::{BrAnon, ReLateBound};
2422 let (fn_sig, abi, env_ty) = match fn_ty.sty {
2423 ty::ty_bare_fn(_, ref f) => (&f.sig, f.abi, None),
2424 ty::ty_closure(closure_did, substs) => {
2425 let typer = common::NormalizingClosureTyper::new(ccx.tcx());
2426 function_type = typer.closure_type(closure_did, substs);
2427 let self_type = self_type_for_closure(ccx, closure_did, fn_ty);
2428 (&function_type.sig, RustCall, Some(self_type))
2430 _ => ccx.sess().bug("expected closure or function.")
2433 let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);
2435 let mut attrs = llvm::AttrBuilder::new();
2436 let ret_ty = fn_sig.output;
2438 // These have an odd calling convention, so we need to manually
2439 // unpack the input ty's
2440 let input_tys = match fn_ty.sty {
2441 ty::ty_closure(..) => {
2442 assert!(abi == RustCall);
2444 match fn_sig.inputs[0].sty {
2445 ty::ty_tup(ref inputs) => {
2446 let mut full_inputs = vec![env_ty.expect("Missing closure environment")];
2447 full_inputs.push_all(inputs);
2450 _ => ccx.sess().bug("expected tuple'd inputs")
2453 ty::ty_bare_fn(..) if abi == RustCall => {
2454 let mut inputs = vec![fn_sig.inputs[0]];
2456 match fn_sig.inputs[1].sty {
2457 ty::ty_tup(ref t_in) => {
2458 inputs.push_all(&t_in[..]);
2461 _ => ccx.sess().bug("expected tuple'd inputs")
2464 _ => fn_sig.inputs.clone()
2467 // Index 0 is the return value of the llvm func, so we start at 1
2468 let mut first_arg_offset = 1;
2469 if let ty::FnConverging(ret_ty) = ret_ty {
2470 // A function pointer is called without the declaration
2471 // available, so we have to apply any attributes with ABI
2472 // implications directly to the call instruction. Right now,
2473 // the only attribute we need to worry about is `sret`.
2474 if type_of::return_uses_outptr(ccx, ret_ty) {
2475 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
2477 // The outptr can be noalias and nocapture because it's entirely
2478 // invisible to the program. We also know it's nonnull as well
2479 // as how many bytes we can dereference
2480 attrs.arg(1, llvm::StructRetAttribute)
2481 .arg(1, llvm::NoAliasAttribute)
2482 .arg(1, llvm::NoCaptureAttribute)
2483 .arg(1, llvm::DereferenceableAttribute(llret_sz));
2485 // Add one more since there's an outptr
2486 first_arg_offset += 1;
2488 // The `noalias` attribute on the return value is useful to a
2489 // function ptr caller.
2491 // `~` pointer return values never alias because ownership
2493 ty::ty_uniq(it) if !common::type_is_sized(ccx.tcx(), it) => {}
2495 attrs.ret(llvm::NoAliasAttribute);
2500 // We can also mark the return value as `dereferenceable` in certain cases
2502 // These are not really pointers but pairs, (pointer, len)
2504 ty::ty_rptr(_, ty::mt { ty: it, .. }) if !common::type_is_sized(ccx.tcx(), it) => {}
2505 ty::ty_uniq(inner) | ty::ty_rptr(_, ty::mt { ty: inner, .. }) => {
2506 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2507 attrs.ret(llvm::DereferenceableAttribute(llret_sz));
2512 if let ty::ty_bool = ret_ty.sty {
2513 attrs.ret(llvm::ZExtAttribute);
2518 for (idx, &t) in input_tys.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2520 // this needs to be first to prevent fat pointers from falling through
2521 _ if !type_is_immediate(ccx, t) => {
2522 let llarg_sz = llsize_of_real(ccx, type_of::type_of(ccx, t));
2524 // For non-immediate arguments the callee gets its own copy of
2525 // the value on the stack, so there are no aliases. It's also
2526 // program-invisible so can't possibly capture
2527 attrs.arg(idx, llvm::NoAliasAttribute)
2528 .arg(idx, llvm::NoCaptureAttribute)
2529 .arg(idx, llvm::DereferenceableAttribute(llarg_sz));
2533 attrs.arg(idx, llvm::ZExtAttribute);
2536 // `~` pointer parameters never alias because ownership is transferred
2537 ty::ty_uniq(inner) => {
2538 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2540 attrs.arg(idx, llvm::NoAliasAttribute)
2541 .arg(idx, llvm::DereferenceableAttribute(llsz));
2544 // `&mut` pointer parameters never alias other parameters, or mutable global data
2546 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
2547 // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on
2548 // memory dependencies rather than pointer equality
2549 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable ||
2550 !ty::type_contents(ccx.tcx(), mt.ty).interior_unsafe() => {
2552 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2553 attrs.arg(idx, llvm::NoAliasAttribute)
2554 .arg(idx, llvm::DereferenceableAttribute(llsz));
2556 if mt.mutbl == ast::MutImmutable {
2557 attrs.arg(idx, llvm::ReadOnlyAttribute);
2560 if let ReLateBound(_, BrAnon(_)) = *b {
2561 attrs.arg(idx, llvm::NoCaptureAttribute);
2565 // When a reference in an argument has no named lifetime, it's impossible for that
2566 // reference to escape this function (returned or stored beyond the call by a closure).
2567 ty::ty_rptr(&ReLateBound(_, BrAnon(_)), mt) => {
2568 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2569 attrs.arg(idx, llvm::NoCaptureAttribute)
2570 .arg(idx, llvm::DereferenceableAttribute(llsz));
2573 // & pointer parameters are also never null and we know exactly how
2574 // many bytes we can dereference
2575 ty::ty_rptr(_, mt) => {
2576 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2577 attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
2586 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2587 pub fn register_fn_llvmty(ccx: &CrateContext,
2590 node_id: ast::NodeId,
2592 llfty: Type) -> ValueRef {
2593 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2595 let llfn = decl_fn(ccx,
2599 ty::FnConverging(ty::mk_nil(ccx.tcx())));
2600 finish_register_fn(ccx, sp, sym, node_id, llfn);
2604 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2605 match *sess.entry_fn.borrow() {
2606 Some((entry_id, _)) => node_id == entry_id,
2611 // Create a _rust_main(args: ~[str]) function which will be called from the
2612 // runtime rust_start function
2613 pub fn create_entry_wrapper(ccx: &CrateContext,
2615 main_llfn: ValueRef) {
2616 let et = ccx.sess().entry_type.get().unwrap();
2618 config::EntryMain => {
2619 create_entry_fn(ccx, main_llfn, true);
2621 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2622 config::EntryNone => {} // Do nothing.
2625 fn create_entry_fn(ccx: &CrateContext,
2626 rust_main: ValueRef,
2627 use_start_lang_item: bool) {
2628 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()],
2631 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil(ccx.tcx()));
2633 // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2634 // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2635 if ccx.sess().target.target.options.is_like_windows {
2636 unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2640 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn,
2641 "top\0".as_ptr() as *const _)
2643 let bld = ccx.raw_builder();
2645 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2647 debuginfo::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2649 let (start_fn, args) = if use_start_lang_item {
2650 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2652 Err(s) => { ccx.sess().fatal(&s[..]); }
2654 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2655 get_item_val(ccx, start_def_id.node)
2657 let start_fn_type = csearch::get_type(ccx.tcx(),
2659 trans_external_path(ccx, start_def_id, start_fn_type)
2663 let opaque_rust_main = llvm::LLVMBuildPointerCast(bld,
2664 rust_main, Type::i8p(ccx).to_ref(),
2665 "rust_main\0".as_ptr() as *const _);
2675 debug!("using user-defined start fn");
2677 get_param(llfn, 0 as c_uint),
2678 get_param(llfn, 1 as c_uint)
2684 let result = llvm::LLVMBuildCall(bld,
2687 args.len() as c_uint,
2690 llvm::LLVMBuildRet(bld, result);
2695 fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, id: ast::NodeId,
2696 ty: Ty<'tcx>, attrs: &[ast::Attribute]) -> String {
2697 match ccx.external_srcs().borrow().get(&id) {
2699 let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2700 debug!("found item {} in other crate...", sym);
2706 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2707 // Use provided name
2708 Some(name) => name.to_string(),
2710 _ => ccx.tcx().map.with_path(id, |path| {
2711 if attr::contains_name(attrs, "no_mangle") {
2713 path.last().unwrap().to_string()
2715 match weak_lang_items::link_name(attrs) {
2716 Some(name) => name.to_string(),
2718 // Usual name mangling
2719 mangle_exported_name(ccx, path, ty, id)
2727 fn contains_null(s: &str) -> bool {
2728 s.bytes().any(|b| b == 0)
2731 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2732 debug!("get_item_val(id=`{}`)", id);
2734 match ccx.item_vals().borrow().get(&id).cloned() {
2735 Some(v) => return v,
2739 let item = ccx.tcx().map.get(id);
2740 debug!("get_item_val: id={} item={:?}", id, item);
2741 let val = match item {
2742 ast_map::NodeItem(i) => {
2743 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2744 let sym = || exported_name(ccx, id, ty, &i.attrs);
2746 let v = match i.node {
2747 ast::ItemStatic(_, _, ref expr) => {
2748 // If this static came from an external crate, then
2749 // we need to get the symbol from csearch instead of
2750 // using the current crate's name/version
2751 // information in the hash of the symbol
2753 debug!("making {}", sym);
2755 // We need the translated value here, because for enums the
2756 // LLVM type is not fully determined by the Rust type.
2757 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2758 let (v, ty) = consts::const_expr(ccx, &**expr, empty_substs);
2759 ccx.static_values().borrow_mut().insert(id, v);
2761 // boolean SSA values are i1, but they have to be stored in i8 slots,
2762 // otherwise some LLVM optimization passes don't work as expected
2763 let llty = if ty::type_is_bool(ty) {
2764 llvm::LLVMInt8TypeInContext(ccx.llcx())
2768 if contains_null(&sym[..]) {
2770 &format!("Illegal null byte in export_name \
2771 value: `{}`", sym));
2773 let buf = CString::new(sym.clone()).unwrap();
2774 let g = llvm::LLVMAddGlobal(ccx.llmod(), llty,
2777 if attr::contains_name(&i.attrs,
2779 llvm::set_thread_local(g, true);
2781 ccx.item_symbols().borrow_mut().insert(i.id, sym);
2786 ast::ItemFn(_, _, abi, _, _) => {
2788 let llfn = if abi == Rust {
2789 register_fn(ccx, i.span, sym, i.id, ty)
2791 foreign::register_rust_fn_with_foreign_abi(ccx,
2796 set_llvm_fn_attrs(ccx, &i.attrs, llfn);
2800 _ => ccx.sess().bug("get_item_val: weird result in table")
2803 match attr::first_attr_value_str_by_name(&i.attrs,
2806 if contains_null(§) {
2807 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`",
2811 let buf = CString::new(sect.as_bytes()).unwrap();
2812 llvm::LLVMSetSection(v, buf.as_ptr());
2821 ast_map::NodeTraitItem(trait_method) => {
2822 debug!("get_item_val(): processing a NodeTraitItem");
2823 match *trait_method {
2824 ast::RequiredMethod(_) | ast::TypeTraitItem(_) => {
2825 ccx.sess().bug("unexpected variant: required trait \
2826 method in get_item_val()");
2828 ast::ProvidedMethod(ref m) => {
2829 register_method(ccx, id, &**m)
2834 ast_map::NodeImplItem(ii) => {
2836 ast::MethodImplItem(ref m) => register_method(ccx, id, &**m),
2837 ast::TypeImplItem(ref typedef) => {
2838 ccx.sess().span_bug(typedef.span,
2839 "unexpected variant: required impl \
2840 method in get_item_val()")
2845 ast_map::NodeForeignItem(ni) => {
2847 ast::ForeignItemFn(..) => {
2848 let abi = ccx.tcx().map.get_foreign_abi(id);
2849 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2850 let name = foreign::link_name(&*ni);
2851 foreign::register_foreign_item_fn(ccx, abi, ty, &name)
2853 ast::ForeignItemStatic(..) => {
2854 foreign::register_static(ccx, &*ni)
2859 ast_map::NodeVariant(ref v) => {
2861 let args = match v.node.kind {
2862 ast::TupleVariantKind(ref args) => args,
2863 ast::StructVariantKind(_) => {
2864 ccx.sess().bug("struct variant kind unexpected in get_item_val")
2867 assert!(args.len() != 0);
2868 let ty = ty::node_id_to_type(ccx.tcx(), id);
2869 let parent = ccx.tcx().map.get_parent(id);
2870 let enm = ccx.tcx().map.expect_item(parent);
2871 let sym = exported_name(ccx,
2876 llfn = match enm.node {
2877 ast::ItemEnum(_, _) => {
2878 register_fn(ccx, (*v).span, sym, id, ty)
2880 _ => ccx.sess().bug("NodeVariant, shouldn't happen")
2882 set_inline_hint(llfn);
2886 ast_map::NodeStructCtor(struct_def) => {
2887 // Only register the constructor if this is a tuple-like struct.
2888 let ctor_id = match struct_def.ctor_id {
2890 ccx.sess().bug("attempt to register a constructor of \
2891 a non-tuple-like struct")
2893 Some(ctor_id) => ctor_id,
2895 let parent = ccx.tcx().map.get_parent(id);
2896 let struct_item = ccx.tcx().map.expect_item(parent);
2897 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2898 let sym = exported_name(ccx,
2901 &struct_item.attrs);
2902 let llfn = register_fn(ccx, struct_item.span,
2904 set_inline_hint(llfn);
2909 ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}",
2914 // All LLVM globals and functions are initially created as external-linkage
2915 // declarations. If `trans_item`/`trans_fn` later turns the declaration
2916 // into a definition, it adjusts the linkage then (using `update_linkage`).
2918 // The exception is foreign items, which have their linkage set inside the
2919 // call to `foreign::register_*` above. We don't touch the linkage after
2920 // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2921 // other item translation functions do).
2923 ccx.item_vals().borrow_mut().insert(id, val);
2927 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2928 m: &ast::Method) -> ValueRef {
2929 let mty = ty::node_id_to_type(ccx.tcx(), id);
2931 let sym = exported_name(ccx, id, mty, &m.attrs);
2933 if let ty::ty_bare_fn(_, ref f) = mty.sty {
2934 let llfn = if f.abi == Rust || f.abi == RustCall {
2935 register_fn(ccx, m.span, sym, id, mty)
2937 foreign::register_rust_fn_with_foreign_abi(ccx, m.span, sym, id)
2939 set_llvm_fn_attrs(ccx, &m.attrs, llfn);
2942 ccx.sess().span_bug(m.span, "expected bare rust function");
2946 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2947 ie: encoder::EncodeInlinedItem<'a>)
2948 -> encoder::EncodeParams<'a, 'tcx> {
2949 encoder::EncodeParams {
2950 diag: cx.sess().diagnostic(),
2952 reexports: cx.export_map(),
2953 item_symbols: cx.item_symbols(),
2954 link_meta: cx.link_meta(),
2955 cstore: &cx.sess().cstore,
2956 encode_inlined_item: ie,
2957 reachable: cx.reachable(),
2961 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2964 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2965 *ty != config::CrateTypeExecutable
2971 let encode_inlined_item: encoder::EncodeInlinedItem =
2972 Box::new(|ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii));
2974 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2975 let metadata = encoder::encode_metadata(encode_parms, krate);
2976 let mut compressed = encoder::metadata_encoding_version.to_vec();
2977 compressed.push_all(&match flate::deflate_bytes(&metadata) {
2978 Some(compressed) => compressed,
2979 None => cx.sess().fatal("failed to compress metadata"),
2981 let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2982 let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2983 let name = format!("rust_metadata_{}_{}",
2984 cx.link_meta().crate_name,
2985 cx.link_meta().crate_hash);
2986 let buf = CString::new(name).unwrap();
2987 let llglobal = unsafe {
2988 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(),
2992 llvm::LLVMSetInitializer(llglobal, llconst);
2993 let name = loader::meta_section_name(cx.sess().target.target.options.is_like_osx);
2994 let name = CString::new(name).unwrap();
2995 llvm::LLVMSetSection(llglobal, name.as_ptr())
3000 /// Find any symbols that are defined in one compilation unit, but not declared
3001 /// in any other compilation unit. Give these symbols internal linkage.
3002 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
3004 let mut declared = HashSet::new();
3006 let iter_globals = |llmod| {
3008 cur: llvm::LLVMGetFirstGlobal(llmod),
3009 step: llvm::LLVMGetNextGlobal,
3013 let iter_functions = |llmod| {
3015 cur: llvm::LLVMGetFirstFunction(llmod),
3016 step: llvm::LLVMGetNextFunction,
3020 // Collect all external declarations in all compilation units.
3021 for ccx in cx.iter() {
3022 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
3023 let linkage = llvm::LLVMGetLinkage(val);
3024 // We only care about external declarations (not definitions)
3025 // and available_externally definitions.
3026 if !(linkage == llvm::ExternalLinkage as c_uint &&
3027 llvm::LLVMIsDeclaration(val) != 0) &&
3028 !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
3032 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
3033 .to_bytes().to_vec();
3034 declared.insert(name);
3038 // Examine each external definition. If the definition is not used in
3039 // any other compilation unit, and is not reachable from other crates,
3040 // then give it internal linkage.
3041 for ccx in cx.iter() {
3042 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
3043 // We only care about external definitions.
3044 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
3045 llvm::LLVMIsDeclaration(val) == 0) {
3049 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
3050 .to_bytes().to_vec();
3051 if !declared.contains(&name) &&
3052 !reachable.contains(str::from_utf8(&name).unwrap()) {
3053 llvm::SetLinkage(val, llvm::InternalLinkage);
3062 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
3065 impl Iterator for ValueIter {
3066 type Item = ValueRef;
3068 fn next(&mut self) -> Option<ValueRef> {
3072 let step: unsafe extern "C" fn(ValueRef) -> ValueRef =
3073 mem::transmute_copy(&self.step);
3084 pub fn trans_crate<'tcx>(analysis: ty::CrateAnalysis<'tcx>)
3085 -> (ty::ctxt<'tcx>, CrateTranslation) {
3086 let ty::CrateAnalysis { ty_cx: tcx, export_map, reachable, name, .. } = analysis;
3087 let krate = tcx.map.krate();
3089 let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
3092 tcx.sess.opts.debug_assertions
3095 // Before we touch LLVM, make sure that multithreading is enabled.
3097 use std::sync::{Once, ONCE_INIT};
3098 static INIT: Once = ONCE_INIT;
3099 static mut POISONED: bool = false;
3101 if llvm::LLVMStartMultithreaded() != 1 {
3102 // use an extra bool to make sure that all future usage of LLVM
3103 // cannot proceed despite the Once not running more than once.
3109 tcx.sess.bug("couldn't enable multi-threaded LLVM");
3113 let link_meta = link::build_link_meta(&tcx.sess, krate, name);
3115 let codegen_units = tcx.sess.opts.cg.codegen_units;
3116 let shared_ccx = SharedCrateContext::new(&link_meta.crate_name,
3126 let ccx = shared_ccx.get_ccx(0);
3128 // First, verify intrinsics.
3129 intrinsic::check_intrinsics(&ccx);
3131 // Next, translate the module.
3133 let _icx = push_ctxt("text");
3134 trans_mod(&ccx, &krate.module);
3138 for ccx in shared_ccx.iter() {
3139 glue::emit_tydescs(&ccx);
3140 if ccx.sess().opts.debuginfo != NoDebugInfo {
3141 debuginfo::finalize(&ccx);
3145 // Translate the metadata.
3146 let metadata = write_metadata(&shared_ccx, krate);
3148 if shared_ccx.sess().trans_stats() {
3149 let stats = shared_ccx.stats();
3150 println!("--- trans stats ---");
3151 println!("n_static_tydescs: {}", stats.n_static_tydescs.get());
3152 println!("n_glues_created: {}", stats.n_glues_created.get());
3153 println!("n_null_glues: {}", stats.n_null_glues.get());
3154 println!("n_real_glues: {}", stats.n_real_glues.get());
3156 println!("n_fns: {}", stats.n_fns.get());
3157 println!("n_monos: {}", stats.n_monos.get());
3158 println!("n_inlines: {}", stats.n_inlines.get());
3159 println!("n_closures: {}", stats.n_closures.get());
3160 println!("fn stats:");
3161 stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
3162 insns_b.cmp(&insns_a)
3164 for tuple in &*stats.fn_stats.borrow() {
3166 (ref name, insns) => {
3167 println!("{} insns, {}", insns, *name);
3172 if shared_ccx.sess().count_llvm_insns() {
3173 for (k, v) in &*shared_ccx.stats().llvm_insns.borrow() {
3174 println!("{:7} {}", *v, *k);
3178 let modules = shared_ccx.iter()
3179 .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
3182 let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
3183 shared_ccx.item_symbols().borrow().get(id).map(|s| s.to_string())
3186 // For the purposes of LTO, we add to the reachable set all of the upstream
3187 // reachable extern fns. These functions are all part of the public ABI of
3188 // the final product, so LTO needs to preserve them.
3189 shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
3190 let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
3191 reachable.extend(syms.into_iter().map(|did| {
3192 csearch::get_symbol(&shared_ccx.sess().cstore, did)
3196 // Make sure that some other crucial symbols are not eliminated from the
3197 // module. This includes the main function, the crate map (used for debug
3198 // log settings and I/O), and finally the curious rust_stack_exhausted
3199 // symbol. This symbol is required for use by the libmorestack library that
3200 // we link in, so we must ensure that this symbol is not internalized (if
3201 // defined in the crate).
3202 reachable.push("main".to_string());
3203 reachable.push("rust_stack_exhausted".to_string());
3205 // referenced from .eh_frame section on some platforms
3206 reachable.push("rust_eh_personality".to_string());
3207 // referenced from rt/rust_try.ll
3208 reachable.push("rust_eh_personality_catch".to_string());
3210 if codegen_units > 1 {
3211 internalize_symbols(&shared_ccx, &reachable.iter().cloned().collect());
3214 let metadata_module = ModuleTranslation {
3215 llcx: shared_ccx.metadata_llcx(),
3216 llmod: shared_ccx.metadata_llmod(),
3218 let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
3219 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
3221 let translation = CrateTranslation {
3223 metadata_module: metadata_module,
3226 reachable: reachable,
3227 crate_formats: formats,
3228 no_builtins: no_builtins,
3231 (shared_ccx.take_tcx(), translation)