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::t 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::t`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 use back::link::{mangle_exported_name};
29 use back::{link, abi};
31 use driver::config::{NoDebugInfo, FullDebugInfo};
32 use driver::session::Session;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
35 use llvm::{ModuleRef, ValueRef, BasicBlockRef};
37 use metadata::{csearch, encoder, loader};
39 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
43 use middle::subst::Subst;
44 use middle::trans::_match;
45 use middle::trans::adt;
46 use middle::trans::build::*;
47 use middle::trans::builder::{Builder, noname};
48 use middle::trans::callee;
49 use middle::trans::cleanup;
50 use middle::trans::cleanup::CleanupMethods;
51 use middle::trans::common::*;
52 use middle::trans::consts;
53 use middle::trans::controlflow;
54 use middle::trans::datum;
55 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
56 use middle::trans::debuginfo;
57 use middle::trans::expr;
58 use middle::trans::foreign;
59 use middle::trans::glue;
60 use middle::trans::inline;
61 use middle::trans::intrinsic;
62 use middle::trans::machine;
63 use middle::trans::machine::{llalign_of_min, llsize_of, llsize_of_real};
64 use middle::trans::meth;
65 use middle::trans::monomorphize;
66 use middle::trans::tvec;
67 use middle::trans::type_::Type;
68 use middle::trans::type_of;
69 use middle::trans::type_of::*;
70 use middle::trans::value::Value;
73 use util::common::indenter;
74 use util::ppaux::{Repr, ty_to_string};
75 use util::sha2::Sha256;
76 use util::nodemap::NodeMap;
78 use arena::TypedArena;
79 use libc::{c_uint, uint64_t};
80 use std::c_str::ToCStr;
81 use std::cell::{Cell, RefCell};
83 use std::{i8, i16, i32, i64};
85 use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel, Rust, RustIntrinsic};
86 use syntax::ast_util::{local_def, is_local};
87 use syntax::attr::AttrMetaMethods;
89 use syntax::codemap::Span;
90 use syntax::parse::token::InternedString;
91 use syntax::visit::Visitor;
93 use syntax::{ast, ast_util, ast_map};
97 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
99 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
100 match task_local_insn_key.get() {
101 Some(ctx) => blk(ctx.borrow().as_slice()),
106 pub fn init_insn_ctxt() {
107 task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
110 pub struct _InsnCtxt {
111 _cannot_construct_outside_of_this_module: ()
115 impl Drop for _InsnCtxt {
117 match task_local_insn_key.get() {
118 Some(ctx) => { ctx.borrow_mut().pop(); }
124 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
125 debug!("new InsnCtxt: {}", s);
126 match task_local_insn_key.get() {
127 Some(ctx) => ctx.borrow_mut().push(s),
130 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
133 pub struct StatRecorder<'a> {
134 ccx: &'a CrateContext,
135 name: Option<String>,
140 impl<'a> StatRecorder<'a> {
141 pub fn new(ccx: &'a CrateContext, name: String) -> StatRecorder<'a> {
142 let start = if ccx.sess().trans_stats() {
143 time::precise_time_ns()
147 let istart = ccx.stats.n_llvm_insns.get();
158 impl<'a> Drop for StatRecorder<'a> {
160 if self.ccx.sess().trans_stats() {
161 let end = time::precise_time_ns();
162 let elapsed = ((end - self.start) / 1_000_000) as uint;
163 let iend = self.ccx.stats.n_llvm_insns.get();
164 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
166 iend - self.istart));
167 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
168 // Reset LLVM insn count to avoid compound costs.
169 self.ccx.stats.n_llvm_insns.set(self.istart);
174 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
175 fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
176 ty: Type, output: ty::t) -> ValueRef {
178 let llfn: ValueRef = name.with_c_str(|buf| {
180 llvm::LLVMGetOrInsertFunction(ccx.llmod, buf, ty.to_ref())
184 match ty::get(output).sty {
185 // functions returning bottom may unwind, but can never return normally
188 llvm::LLVMAddFunctionAttribute(llfn,
189 llvm::FunctionIndex as c_uint,
190 llvm::NoReturnAttribute as uint64_t)
196 if ccx.tcx.sess.opts.cg.no_redzone {
198 llvm::LLVMAddFunctionAttribute(llfn,
199 llvm::FunctionIndex as c_uint,
200 llvm::NoRedZoneAttribute as uint64_t)
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() {
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::t) -> ValueRef {
220 decl_fn(ccx, name, llvm::CCallConv, ty, 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.find_equiv(&name) {
232 Some(n) => return *n,
235 let f = decl_fn(ccx, name, cc, ty, output);
236 externs.insert(name.to_string(), f);
240 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
241 match ccx.externs.borrow().find_equiv(&name) {
242 Some(n) => return *n,
246 let f = decl_rust_fn(ccx, fn_ty, name);
248 csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
249 set_llvm_fn_attrs(attrs.as_slice(), f)
252 ccx.externs.borrow_mut().insert(name.to_string(), f);
256 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
257 let (inputs, output, has_env) = match ty::get(fn_ty).sty {
258 ty::ty_bare_fn(ref f) => (f.sig.inputs.clone(), f.sig.output, false),
259 ty::ty_closure(ref f) => (f.sig.inputs.clone(), f.sig.output, true),
260 _ => fail!("expected closure or fn")
263 let llfty = type_of_rust_fn(ccx, has_env, inputs.as_slice(), output);
264 let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, output);
265 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
266 for &(idx, attr) in attrs.iter() {
268 llvm::LLVMAddFunctionAttribute(llfn, idx as c_uint, attr);
275 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
276 let llfn = decl_rust_fn(ccx, fn_ty, name);
277 llvm::SetLinkage(llfn, llvm::InternalLinkage);
281 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
282 name: &str, ty: Type) -> ValueRef {
283 match externs.find_equiv(&name) {
284 Some(n) => return *n,
288 let c = name.with_c_str(|buf| {
289 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
291 externs.insert(name.to_string(), c);
296 // Returns a pointer to the body for the box. The box may be an opaque
297 // box. The result will be casted to the type of body_t, if it is statically
299 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
300 let _icx = push_ctxt("at_box_body");
302 let ty = Type::at_box(ccx, type_of(ccx, body_t));
303 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
304 GEPi(bcx, boxptr, [0u, abi::box_field_body])
307 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
308 match bcx.tcx().lang_items.require(it) {
311 bcx.sess().fatal(format!("allocation of `{}` {}",
312 bcx.ty_to_string(info_ty),
318 // The following malloc_raw_dyn* functions allocate a box to contain
319 // a given type, but with a potentially dynamic size.
321 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
326 let _icx = push_ctxt("malloc_raw_exchange");
330 let r = callee::trans_lang_call(bcx,
331 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
335 let llty_ptr = type_of::type_of(ccx, ptr_ty);
336 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
339 pub fn malloc_raw_dyn_managed<'a>(
345 let _icx = push_ctxt("malloc_raw_managed");
348 let langcall = require_alloc_fn(bcx, t, alloc_fn);
350 // Grab the TypeRef type of box_ptr_ty.
351 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
352 let llty = type_of(ccx, box_ptr_ty);
353 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
356 let drop_glue = glue::get_drop_glue(ccx, t);
357 let r = callee::trans_lang_call(
361 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
366 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
369 // Type descriptor and type glue stuff
371 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
372 match ccx.tydescs.borrow().find(&t) {
373 Some(inf) => return inf.clone(),
377 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
378 let inf = Rc::new(glue::declare_tydesc(ccx, t));
380 ccx.tydescs.borrow_mut().insert(t, inf.clone());
384 #[allow(dead_code)] // useful
385 pub fn set_optimize_for_size(f: ValueRef) {
386 llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
389 pub fn set_no_inline(f: ValueRef) {
390 llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
393 #[allow(dead_code)] // useful
394 pub fn set_no_unwind(f: ValueRef) {
395 llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
398 // Tell LLVM to emit the information necessary to unwind the stack for the
400 pub fn set_uwtable(f: ValueRef) {
401 llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
404 pub fn set_inline_hint(f: ValueRef) {
405 llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
408 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
410 // Set the inline hint if there is one
411 match find_inline_attr(attrs) {
412 InlineHint => set_inline_hint(llfn),
413 InlineAlways => set_always_inline(llfn),
414 InlineNever => set_no_inline(llfn),
415 InlineNone => { /* fallthrough */ }
418 // Add the no-split-stack attribute if requested
419 if contains_name(attrs, "no_split_stack") {
420 unset_split_stack(llfn);
423 if contains_name(attrs, "cold") {
425 llvm::LLVMAddFunctionAttribute(llfn,
426 llvm::FunctionIndex as c_uint,
427 llvm::ColdAttribute as uint64_t)
432 pub fn set_always_inline(f: ValueRef) {
433 llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
436 pub fn set_split_stack(f: ValueRef) {
437 "split-stack".with_c_str(|buf| {
438 unsafe { llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
442 pub fn unset_split_stack(f: ValueRef) {
443 "split-stack".with_c_str(|buf| {
444 unsafe { llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
448 // Double-check that we never ask LLVM to declare the same symbol twice. It
449 // silently mangles such symbols, breaking our linkage model.
450 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
451 if ccx.all_llvm_symbols.borrow().contains(&sym) {
452 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
454 ccx.all_llvm_symbols.borrow_mut().insert(sym);
458 pub fn get_res_dtor(ccx: &CrateContext,
461 parent_id: ast::DefId,
462 substs: &subst::Substs)
464 let _icx = push_ctxt("trans_res_dtor");
465 let did = if did.krate != ast::LOCAL_CRATE {
466 inline::maybe_instantiate_inline(ccx, did)
471 if !substs.types.is_empty() {
472 assert_eq!(did.krate, ast::LOCAL_CRATE);
474 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
475 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
478 } else if did.krate == ast::LOCAL_CRATE {
479 get_item_val(ccx, did.node)
482 let name = csearch::get_symbol(&ccx.sess().cstore, did);
483 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
484 let llty = type_of_dtor(ccx, class_ty);
485 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
486 [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
488 &mut *ccx.externs.borrow_mut(),
496 // Structural comparison: a rather involved form of glue.
497 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
498 if cx.sess().opts.cg.save_temps {
501 llvm::LLVMSetValueName(v, buf)
508 // Used only for creating scalar comparison glue.
509 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
511 pub fn compare_scalar_types<'a>(
518 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
520 match ty::get(t).sty {
521 ty::ty_nil => f(nil_type),
522 ty::ty_bool | ty::ty_ptr(_) |
523 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
524 ty::ty_int(_) => f(signed_int),
525 ty::ty_float(_) => f(floating_point),
526 // Should never get here, because t is scalar.
527 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
532 // A helper function to do the actual comparison of scalar values.
533 pub fn compare_scalar_values<'a>(
540 let _icx = push_ctxt("compare_scalar_values");
541 fn die(cx: &Block) -> ! {
542 cx.sess().bug("compare_scalar_values: must be a comparison operator");
546 // We don't need to do actual comparisons for nil.
547 // () == () holds but () < () does not.
549 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(cx.ccx(), true),
550 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(cx.ccx(), false),
551 // refinements would be nice
557 ast::BiEq => llvm::RealOEQ,
558 ast::BiNe => llvm::RealUNE,
559 ast::BiLt => llvm::RealOLT,
560 ast::BiLe => llvm::RealOLE,
561 ast::BiGt => llvm::RealOGT,
562 ast::BiGe => llvm::RealOGE,
565 return FCmp(cx, cmp, lhs, rhs);
569 ast::BiEq => llvm::IntEQ,
570 ast::BiNe => llvm::IntNE,
571 ast::BiLt => llvm::IntSLT,
572 ast::BiLe => llvm::IntSLE,
573 ast::BiGt => llvm::IntSGT,
574 ast::BiGe => llvm::IntSGE,
577 return ICmp(cx, cmp, lhs, rhs);
581 ast::BiEq => llvm::IntEQ,
582 ast::BiNe => llvm::IntNE,
583 ast::BiLt => llvm::IntULT,
584 ast::BiLe => llvm::IntULE,
585 ast::BiGt => llvm::IntUGT,
586 ast::BiGe => llvm::IntUGE,
589 return ICmp(cx, cmp, lhs, rhs);
594 pub fn compare_simd_types(
602 match ty::get(t).sty {
604 // The comparison operators for floating point vectors are challenging.
605 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
606 // then bitcast to a floating point vector, the result will be `-NaN`
607 // for each truth value. Because of this they are unsupported.
608 cx.sess().bug("compare_simd_types: comparison operators \
609 not supported for floating point SIMD types")
611 ty::ty_uint(_) | ty::ty_int(_) => {
613 ast::BiEq => llvm::IntEQ,
614 ast::BiNe => llvm::IntNE,
615 ast::BiLt => llvm::IntSLT,
616 ast::BiLe => llvm::IntSLE,
617 ast::BiGt => llvm::IntSGT,
618 ast::BiGe => llvm::IntSGE,
619 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
621 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
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(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
628 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
632 pub type val_and_ty_fn<'r,'b> =
633 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
635 // Iterates through the elements of a structural type.
636 pub fn iter_structural_ty<'r,
641 f: val_and_ty_fn<'r,'b>)
643 let _icx = push_ctxt("iter_structural_ty");
650 variant: &ty::VariantInfo,
651 substs: &subst::Substs,
652 f: val_and_ty_fn<'r,'b>)
654 let _icx = push_ctxt("iter_variant");
658 for (i, &arg) in variant.args.iter().enumerate() {
660 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
661 arg.subst(tcx, substs));
667 match ty::get(t).sty {
668 ty::ty_struct(..) => {
669 let repr = adt::represent_type(cx.ccx(), t);
670 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
671 for (i, field_ty) in field_tys.iter().enumerate() {
672 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
673 cx = f(cx, llfld_a, field_ty.mt.ty);
677 ty::ty_vec(_, Some(n)) => {
678 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
679 let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
680 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
682 ty::ty_tup(ref args) => {
683 let repr = adt::represent_type(cx.ccx(), t);
684 for (i, arg) in args.iter().enumerate() {
685 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
686 cx = f(cx, llfld_a, *arg);
689 ty::ty_enum(tid, ref substs) => {
693 let repr = adt::represent_type(ccx, t);
694 let variants = ty::enum_variants(ccx.tcx(), tid);
695 let n_variants = (*variants).len();
697 // NB: we must hit the discriminant first so that structural
698 // comparison know not to proceed when the discriminants differ.
700 match adt::trans_switch(cx, &*repr, av) {
701 (_match::single, None) => {
702 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
705 (_match::switch, Some(lldiscrim_a)) => {
706 cx = f(cx, lldiscrim_a, ty::mk_int());
707 let unr_cx = fcx.new_temp_block("enum-iter-unr");
709 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
711 let next_cx = fcx.new_temp_block("enum-iter-next");
713 for variant in (*variants).iter() {
716 format!("enum-iter-variant-{}",
717 variant.disr_val.to_string().as_slice())
719 match adt::trans_case(cx, &*repr, variant.disr_val) {
720 _match::single_result(r) => {
721 AddCase(llswitch, r.val, variant_cx.llbb)
723 _ => ccx.sess().unimpl("value from adt::trans_case \
724 in iter_structural_ty")
727 iter_variant(variant_cx,
733 Br(variant_cx, next_cx.llbb);
737 _ => ccx.sess().unimpl("value from adt::trans_switch \
738 in iter_structural_ty")
741 _ => cx.sess().unimpl("type in iter_structural_ty")
746 pub fn cast_shift_expr_rhs<'a>(
752 cast_shift_rhs(op, lhs, rhs,
753 |a,b| Trunc(cx, a, b),
754 |a,b| ZExt(cx, a, b))
757 pub fn cast_shift_const_rhs(op: ast::BinOp,
758 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
759 cast_shift_rhs(op, lhs, rhs,
760 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
761 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
764 pub fn cast_shift_rhs(op: ast::BinOp,
767 trunc: |ValueRef, Type| -> ValueRef,
768 zext: |ValueRef, Type| -> ValueRef)
770 // Shifts may have any size int on the rhs
772 if ast_util::is_shift_binop(op) {
773 let mut rhs_llty = val_ty(rhs);
774 let mut lhs_llty = val_ty(lhs);
775 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
776 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
777 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
778 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
781 } else if lhs_sz > rhs_sz {
782 // FIXME (#1877: If shifting by negative
783 // values becomes not undefined then this is wrong.
794 pub fn fail_if_zero_or_overflows<'a>(
802 let (zero_text, overflow_text) = if divrem == ast::BiDiv {
803 ("attempted to divide by zero",
804 "attempted to divide with overflow")
806 ("attempted remainder with a divisor of zero",
807 "attempted remainder with overflow")
809 let (is_zero, is_signed) = match ty::get(rhs_t).sty {
811 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
812 (ICmp(cx, llvm::IntEQ, rhs, zero), true)
815 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
816 (ICmp(cx, llvm::IntEQ, rhs, zero), false)
819 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
820 ty_to_string(cx.tcx(), rhs_t)).as_slice());
823 let bcx = with_cond(cx, is_zero, |bcx| {
824 controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
827 // To quote LLVM's documentation for the sdiv instruction:
829 // Division by zero leads to undefined behavior. Overflow also leads
830 // to undefined behavior; this is a rare case, but can occur, for
831 // example, by doing a 32-bit division of -2147483648 by -1.
833 // In order to avoid undefined behavior, we perform runtime checks for
834 // signed division/remainder which would trigger overflow. For unsigned
835 // integers, no action beyond checking for zero need be taken.
837 let (llty, min) = match ty::get(rhs_t).sty {
839 let llty = Type::int_from_ty(cx.ccx(), t);
841 ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
842 ast::TyI => i64::MIN as u64,
843 ast::TyI8 => i8::MIN as u64,
844 ast::TyI16 => i16::MIN as u64,
845 ast::TyI32 => i32::MIN as u64,
846 ast::TyI64 => i64::MIN as u64,
852 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
853 C_integral(llty, -1, false));
854 with_cond(bcx, minus_one, |bcx| {
855 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
856 C_integral(llty, min, true));
857 with_cond(bcx, is_min, |bcx| {
858 controlflow::trans_fail(bcx, span,
859 InternedString::new(overflow_text))
867 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
868 let name = csearch::get_symbol(&ccx.sess().cstore, did);
869 match ty::get(t).sty {
870 ty::ty_bare_fn(ref fn_ty) => {
871 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
872 ccx.sess().targ_cfg.arch) {
874 get_extern_rust_fn(ccx, t, name.as_slice(), did)
876 Some(RustIntrinsic) => {
877 ccx.sess().bug("unexpected intrinsic in trans_external_path")
880 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
881 name.as_slice(), None)
885 ty::ty_closure(_) => {
886 get_extern_rust_fn(ccx, t, name.as_slice(), did)
889 let llty = type_of(ccx, t);
890 get_extern_const(&mut *ccx.externs.borrow_mut(),
901 llargs: Vec<ValueRef> ,
903 call_info: Option<NodeInfo>)
904 -> (ValueRef, &'a Block<'a>) {
905 let _icx = push_ctxt("invoke_");
906 if bcx.unreachable.get() {
907 return (C_null(Type::i8(bcx.ccx())), bcx);
910 let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
912 match bcx.opt_node_id {
914 debug!("invoke at ???");
917 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
921 if need_invoke(bcx) {
922 debug!("invoking {} at {}", llfn, bcx.llbb);
923 for &llarg in llargs.iter() {
924 debug!("arg: {}", llarg);
926 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
927 let landing_pad = bcx.fcx.get_landing_pad();
930 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
931 None => debuginfo::clear_source_location(bcx.fcx)
934 let llresult = Invoke(bcx,
939 attributes.as_slice());
940 return (llresult, normal_bcx);
942 debug!("calling {} at {}", llfn, bcx.llbb);
943 for &llarg in llargs.iter() {
944 debug!("arg: {}", llarg);
948 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
949 None => debuginfo::clear_source_location(bcx.fcx)
952 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes.as_slice());
953 return (llresult, bcx);
957 pub fn need_invoke(bcx: &Block) -> bool {
958 if bcx.sess().no_landing_pads() {
962 // Avoid using invoke if we are already inside a landing pad.
967 bcx.fcx.needs_invoke()
970 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
971 let _icx = push_ctxt("load_if_immediate");
972 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
976 pub fn load_ty(cx: &Block, ptr: ValueRef, t: ty::t) -> ValueRef {
978 * Helper for loading values from memory. Does the necessary conversion if
979 * the in-memory type differs from the type used for SSA values. Also
980 * handles various special cases where the type gives us better information
981 * about what we are loading.
983 if type_is_zero_size(cx.ccx(), t) {
984 C_undef(type_of::type_of(cx.ccx(), t))
985 } else if ty::type_is_bool(t) {
986 Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
987 } else if ty::type_is_char(t) {
988 // a char is a unicode codepoint, and so takes values from 0
989 // to 0x10FFFF inclusive only.
990 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
996 pub fn store_ty(cx: &Block, v: ValueRef, dst: ValueRef, t: ty::t) {
998 * Helper for storing values in memory. Does the necessary conversion if
999 * the in-memory type differs from the type used for SSA values.
1001 if ty::type_is_bool(t) {
1002 Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1008 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1009 match local.pat.node {
1010 ast::PatWild => true, _ => false
1014 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1016 debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
1017 let _indenter = indenter();
1018 let _icx = push_ctxt("init_local");
1019 _match::store_local(bcx, local)
1022 pub fn raw_block<'a>(
1023 fcx: &'a FunctionContext<'a>,
1025 llbb: BasicBlockRef)
1027 Block::new(llbb, is_lpad, None, fcx)
1030 pub fn with_cond<'a>(
1033 f: |&'a Block<'a>| -> &'a Block<'a>)
1035 let _icx = push_ctxt("with_cond");
1037 let next_cx = fcx.new_temp_block("next");
1038 let cond_cx = fcx.new_temp_block("cond");
1039 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1040 let after_cx = f(cond_cx);
1041 if !after_cx.terminated.get() {
1042 Br(after_cx, next_cx.llbb);
1047 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1048 let _icx = push_ctxt("call_memcpy");
1050 let key = match ccx.sess().targ_cfg.arch {
1051 X86 | Arm | Mips | Mipsel => "llvm.memcpy.p0i8.p0i8.i32",
1052 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1054 let memcpy = ccx.get_intrinsic(&key);
1055 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1056 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1057 let size = IntCast(cx, n_bytes, ccx.int_type);
1058 let align = C_i32(ccx, align as i32);
1059 let volatile = C_bool(ccx, false);
1060 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1063 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1064 let _icx = push_ctxt("memcpy_ty");
1065 let ccx = bcx.ccx();
1066 if ty::type_is_structural(t) {
1067 let llty = type_of::type_of(ccx, t);
1068 let llsz = llsize_of(ccx, llty);
1069 let llalign = llalign_of_min(ccx, llty);
1070 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1072 Store(bcx, Load(bcx, src), dst);
1076 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1077 if cx.unreachable.get() { return; }
1078 let _icx = push_ctxt("zero_mem");
1081 let llty = type_of::type_of(ccx, t);
1082 memzero(&B(bcx), llptr, llty);
1085 // Always use this function instead of storing a zero constant to the memory
1086 // in question. If you store a zero constant, LLVM will drown in vreg
1087 // allocation for large data structures, and the generated code will be
1088 // awful. (A telltale sign of this is large quantities of
1089 // `mov [byte ptr foo],0` in the generated code.)
1090 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1091 let _icx = push_ctxt("memzero");
1094 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1095 X86 | Arm | Mips | Mipsel => "llvm.memset.p0i8.i32",
1096 X86_64 => "llvm.memset.p0i8.i64"
1099 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1100 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1101 let llzeroval = C_u8(ccx, 0);
1102 let size = machine::llsize_of(ccx, ty);
1103 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1104 let volatile = C_bool(ccx, false);
1105 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1108 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1109 let _icx = push_ctxt("alloc_ty");
1110 let ccx = bcx.ccx();
1111 let ty = type_of::type_of(ccx, t);
1112 assert!(!ty::type_has_params(t));
1113 let val = alloca(bcx, ty, name);
1117 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1118 alloca_maybe_zeroed(cx, ty, name, false)
1121 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1122 let _icx = push_ctxt("alloca");
1123 if cx.unreachable.get() {
1125 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1128 debuginfo::clear_source_location(cx.fcx);
1129 let p = Alloca(cx, ty, name);
1131 let b = cx.fcx.ccx.builder();
1132 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1138 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1139 let _icx = push_ctxt("arrayalloca");
1140 if cx.unreachable.get() {
1142 return llvm::LLVMGetUndef(ty.to_ref());
1145 debuginfo::clear_source_location(cx.fcx);
1146 return ArrayAlloca(cx, ty, v);
1149 // Creates and returns space for, or returns the argument representing, the
1150 // slot where the return value of the function must go.
1151 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1154 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1155 llvm::LLVMGetParam(fcx.llfn, 0)
1157 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1158 AllocaFcx(fcx, lloutputtype, "__make_return_pointer")
1163 // NB: must keep 4 fns in sync:
1166 // - create_datums_for_fn_args.
1170 // Be warned! You must call `init_function` before doing anything with the
1171 // returned function context.
1172 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1177 param_substs: &'a param_substs,
1179 block_arena: &'a TypedArena<Block<'a>>)
1180 -> FunctionContext<'a> {
1181 param_substs.validate();
1183 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1187 ccx.tcx.map.path_to_string(id).to_string()
1189 id, param_substs.repr(ccx.tcx()));
1191 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1192 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1193 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1195 let mut fcx = FunctionContext {
1198 llretptr: Cell::new(None),
1199 alloca_insert_pt: Cell::new(None),
1200 llreturn: Cell::new(None),
1201 personality: Cell::new(None),
1202 caller_expects_out_pointer: uses_outptr,
1203 llargs: RefCell::new(NodeMap::new()),
1204 lllocals: RefCell::new(NodeMap::new()),
1205 llupvars: RefCell::new(NodeMap::new()),
1207 param_substs: param_substs,
1209 block_arena: block_arena,
1211 debug_context: debug_context,
1212 scopes: RefCell::new(Vec::new())
1216 fcx.llenv = Some(unsafe {
1217 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1224 /// Performs setup on a newly created function, creating the entry scope block
1225 /// and allocating space for the return pointer.
1226 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1228 output_type: ty::t) -> &'a Block<'a> {
1229 let entry_bcx = fcx.new_temp_block("entry-block");
1231 // Use a dummy instruction as the insertion point for all allocas.
1232 // This is later removed in FunctionContext::cleanup.
1233 fcx.alloca_insert_pt.set(Some(unsafe {
1234 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1235 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1238 // This shouldn't need to recompute the return type,
1239 // as new_fn_ctxt did it already.
1240 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1242 if !return_type_is_void(fcx.ccx, substd_output_type) {
1243 // If the function returns nil/bot, there is no real return
1244 // value, so do not set `llretptr`.
1245 if !skip_retptr || fcx.caller_expects_out_pointer {
1246 // Otherwise, we normally allocate the llretptr, unless we
1247 // have been instructed to skip it for immediate return
1249 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1256 // NB: must keep 4 fns in sync:
1259 // - create_datums_for_fn_args.
1263 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1264 use middle::trans::datum::{ByRef, ByValue};
1267 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1271 // work around bizarre resolve errors
1272 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1273 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1275 // create_datums_for_fn_args: creates rvalue datums for each of the
1276 // incoming function arguments. These will later be stored into
1277 // appropriate lvalue datums.
1278 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1280 -> Vec<RvalueDatum> {
1281 let _icx = push_ctxt("create_datums_for_fn_args");
1283 // Return an array wrapping the ValueRefs that we get from
1284 // llvm::LLVMGetParam for each argument into datums.
1285 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1286 let llarg = unsafe {
1287 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1289 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1293 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1294 arg_scope: cleanup::CustomScopeIndex,
1297 arg_datums: Vec<RvalueDatum> )
1299 debug!("copy_args_to_allocas");
1301 let _icx = push_ctxt("copy_args_to_allocas");
1304 let arg_scope_id = cleanup::CustomScope(arg_scope);
1306 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1307 // For certain mode/type combinations, the raw llarg values are passed
1308 // by value. However, within the fn body itself, we want to always
1309 // have all locals and arguments be by-ref so that we can cancel the
1310 // cleanup and for better interaction with LLVM's debug info. So, if
1311 // the argument would be passed by value, we store it into an alloca.
1312 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1313 // the event it's not truly needed.
1315 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1317 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1318 debuginfo::create_argument_metadata(bcx, &args[i]);
1325 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1326 // and builds the return block.
1327 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1328 last_bcx: &'a Block<'a>,
1330 let _icx = push_ctxt("finish_fn");
1332 // This shouldn't need to recompute the return type,
1333 // as new_fn_ctxt did it already.
1334 let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1336 let ret_cx = match fcx.llreturn.get() {
1338 if !last_bcx.terminated.get() {
1339 Br(last_bcx, llreturn);
1341 raw_block(fcx, false, llreturn)
1345 build_return_block(fcx, ret_cx, substd_retty);
1346 debuginfo::clear_source_location(fcx);
1350 // Builds the return block for a function.
1351 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block, retty: ty::t) {
1352 // Return the value if this function immediate; otherwise, return void.
1353 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1354 return RetVoid(ret_cx);
1357 let retptr = Value(fcx.llretptr.get().unwrap());
1358 let retval = match retptr.get_dominating_store(ret_cx) {
1359 // If there's only a single store to the ret slot, we can directly return
1360 // the value that was stored and omit the store and the alloca
1362 let retval = s.get_operand(0).unwrap().get();
1363 s.erase_from_parent();
1365 if retptr.has_no_uses() {
1366 retptr.erase_from_parent();
1369 if ty::type_is_bool(retty) {
1370 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1375 // Otherwise, load the return value from the ret slot
1376 None => load_ty(ret_cx, fcx.llretptr.get().unwrap(), retty)
1379 Ret(ret_cx, retval);
1382 // trans_closure: Builds an LLVM function out of a source function.
1383 // If the function closes over its environment a closure will be
1385 pub fn trans_closure(ccx: &CrateContext,
1389 param_substs: ¶m_substs,
1391 _attributes: &[ast::Attribute],
1393 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1394 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1396 let _icx = push_ctxt("trans_closure");
1397 set_uwtable(llfndecl);
1399 debug!("trans_closure(..., param_substs={})",
1400 param_substs.repr(ccx.tcx()));
1402 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1403 ty::ty_closure(_) => true,
1407 let arena = TypedArena::new();
1408 let fcx = new_fn_ctxt(ccx,
1416 let mut bcx = init_function(&fcx, false, output_type);
1418 // cleanup scope for the incoming arguments
1419 let arg_scope = fcx.push_custom_cleanup_scope();
1421 let block_ty = node_id_type(bcx, body.id);
1423 // Set up arguments to the function.
1424 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1425 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1427 bcx = copy_args_to_allocas(&fcx,
1430 decl.inputs.as_slice(),
1433 bcx = maybe_load_env(bcx);
1435 // Up until here, IR instructions for this function have explicitly not been annotated with
1436 // source code location, so we don't step into call setup code. From here on, source location
1437 // emitting should be enabled.
1438 debuginfo::start_emitting_source_locations(&fcx);
1440 let dest = match fcx.llretptr.get() {
1441 Some(e) => {expr::SaveIn(e)}
1443 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1448 // This call to trans_block is the place where we bridge between
1449 // translation calls that don't have a return value (trans_crate,
1450 // trans_mod, trans_item, et cetera) and those that do
1451 // (trans_block, trans_expr, et cetera).
1452 bcx = controlflow::trans_block(bcx, body, dest);
1454 match fcx.llreturn.get() {
1456 Br(bcx, fcx.return_exit_block());
1457 fcx.pop_custom_cleanup_scope(arg_scope);
1460 // Microoptimization writ large: avoid creating a separate
1461 // llreturn basic block
1462 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1466 // Put return block after all other blocks.
1467 // This somewhat improves single-stepping experience in debugger.
1469 let llreturn = fcx.llreturn.get();
1470 for &llreturn in llreturn.iter() {
1471 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1475 // Insert the mandatory first few basic blocks before lltop.
1476 finish_fn(&fcx, bcx, output_type);
1479 // trans_fn: creates an LLVM function corresponding to a source language
1481 pub fn trans_fn(ccx: &CrateContext,
1485 param_substs: ¶m_substs,
1487 attrs: &[ast::Attribute]) {
1488 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_string(id).to_string());
1489 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1490 let _icx = push_ctxt("trans_fn");
1491 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1492 trans_closure(ccx, decl, body, llfndecl,
1493 param_substs, id, attrs, output_type, |bcx| bcx);
1496 pub fn trans_enum_variant(ccx: &CrateContext,
1497 _enum_id: ast::NodeId,
1498 variant: &ast::Variant,
1499 _args: &[ast::VariantArg],
1501 param_substs: ¶m_substs,
1502 llfndecl: ValueRef) {
1503 let _icx = push_ctxt("trans_enum_variant");
1505 trans_enum_variant_or_tuple_like_struct(
1513 pub fn trans_tuple_struct(ccx: &CrateContext,
1514 _fields: &[ast::StructField],
1515 ctor_id: ast::NodeId,
1516 param_substs: ¶m_substs,
1517 llfndecl: ValueRef) {
1518 let _icx = push_ctxt("trans_tuple_struct");
1520 trans_enum_variant_or_tuple_like_struct(
1528 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1529 ctor_id: ast::NodeId,
1531 param_substs: ¶m_substs,
1532 llfndecl: ValueRef) {
1533 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1534 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1536 let result_ty = match ty::get(ctor_ty).sty {
1537 ty::ty_bare_fn(ref bft) => bft.sig.output,
1538 _ => ccx.sess().bug(
1539 format!("trans_enum_variant_or_tuple_like_struct: \
1540 unexpected ctor return type {}",
1541 ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
1544 let arena = TypedArena::new();
1545 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1546 param_substs, None, &arena);
1547 let bcx = init_function(&fcx, false, result_ty);
1549 let arg_tys = ty::ty_fn_args(ctor_ty);
1551 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1553 if !type_is_zero_size(fcx.ccx, result_ty) {
1554 let repr = adt::represent_type(ccx, result_ty);
1555 adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1556 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1557 let lldestptr = adt::trans_field_ptr(bcx,
1559 fcx.llretptr.get().unwrap(),
1562 arg_datum.store_to(bcx, lldestptr);
1566 finish_fn(&fcx, bcx, result_ty);
1569 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1570 sp: Span, id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1572 for variant in enum_definition.variants.iter() {
1573 let disr_val = vi[*i].disr_val;
1576 match variant.node.kind {
1577 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1578 let llfn = get_item_val(ccx, variant.node.id);
1579 trans_enum_variant(ccx, id, &**variant, args.as_slice(),
1580 disr_val, ¶m_substs::empty(), llfn);
1582 ast::TupleVariantKind(_) => {
1585 ast::StructVariantKind(struct_def) => {
1586 trans_struct_def(ccx, struct_def);
1591 enum_variant_size_lint(ccx, enum_definition, sp, id);
1594 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1595 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1597 let levels = ccx.tcx.node_lint_levels.borrow();
1598 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
1599 let lvlsrc = match levels.find(&(id, lint_id)) {
1600 None | Some(&(lint::Allow, _)) => return,
1601 Some(&lvlsrc) => lvlsrc,
1604 let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
1606 adt::General(_, ref variants) => {
1607 for var in variants.iter() {
1609 for field in var.fields.iter().skip(1) {
1610 // skip the discriminant
1611 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1616 _ => { /* its size is either constant or unimportant */ }
1619 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1620 |(l, s, li), (idx, &size)|
1623 } else if size > s {
1630 // we only warn if the largest variant is at least thrice as large as
1631 // the second-largest.
1632 if largest > slargest * 3 && slargest > 0 {
1633 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1634 // pass for the latter already ran.
1635 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
1637 format!("enum variant is more than three times larger \
1638 ({} bytes) than the next largest (ignoring padding)",
1639 largest).as_slice());
1641 ccx.sess().span_note(enum_def.variants.get(largest_index).span,
1642 "this variant is the largest");
1646 pub struct TransItemVisitor<'a> {
1647 pub ccx: &'a CrateContext,
1650 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1651 fn visit_item(&mut self, i: &ast::Item, _:()) {
1652 trans_item(self.ccx, i);
1656 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1657 let _icx = push_ctxt("trans_item");
1659 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1661 let llfndecl = get_item_val(ccx, item.id);
1662 foreign::trans_rust_fn_with_foreign_abi(
1663 ccx, &**decl, &**body, item.attrs.as_slice(), llfndecl, item.id);
1664 } else if !generics.is_type_parameterized() {
1665 let llfn = get_item_val(ccx, item.id);
1670 ¶m_substs::empty(),
1672 item.attrs.as_slice());
1674 // Be sure to travel more than just one layer deep to catch nested
1675 // items in blocks and such.
1676 let mut v = TransItemVisitor{ ccx: ccx };
1677 v.visit_block(&**body, ());
1680 ast::ItemImpl(ref generics, _, _, ref ms) => {
1681 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1683 ast::ItemMod(ref m) => {
1686 ast::ItemEnum(ref enum_definition, ref generics) => {
1687 if !generics.is_type_parameterized() {
1688 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1690 trans_enum_def(ccx, enum_definition, item.span, item.id, vi.as_slice(), &mut i);
1693 ast::ItemStatic(_, m, ref expr) => {
1694 // Recurse on the expression to catch items in blocks
1695 let mut v = TransItemVisitor{ ccx: ccx };
1696 v.visit_expr(&**expr, ());
1697 consts::trans_const(ccx, m, item.id);
1698 // Do static_assert checking. It can't really be done much earlier
1699 // because we need to get the value of the bool out of LLVM
1700 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1701 if m == ast::MutMutable {
1702 ccx.sess().span_fatal(expr.span,
1703 "cannot have static_assert on a mutable \
1707 let v = ccx.const_values.borrow().get_copy(&item.id);
1709 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1710 ccx.sess().span_fatal(expr.span, "static assertion failed");
1715 ast::ItemForeignMod(ref foreign_mod) => {
1716 foreign::trans_foreign_mod(ccx, foreign_mod);
1718 ast::ItemStruct(struct_def, ref generics) => {
1719 if !generics.is_type_parameterized() {
1720 trans_struct_def(ccx, struct_def);
1723 ast::ItemTrait(..) => {
1724 // Inside of this trait definition, we won't be actually translating any
1725 // functions, but the trait still needs to be walked. Otherwise default
1726 // methods with items will not get translated and will cause ICE's when
1727 // metadata time comes around.
1728 let mut v = TransItemVisitor{ ccx: ccx };
1729 visit::walk_item(&mut v, item, ());
1731 _ => {/* fall through */ }
1735 pub fn trans_struct_def(ccx: &CrateContext, struct_def: Gc<ast::StructDef>) {
1736 // If this is a tuple-like struct, translate the constructor.
1737 match struct_def.ctor_id {
1738 // We only need to translate a constructor if there are fields;
1739 // otherwise this is a unit-like struct.
1740 Some(ctor_id) if struct_def.fields.len() > 0 => {
1741 let llfndecl = get_item_val(ccx, ctor_id);
1742 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1743 ctor_id, ¶m_substs::empty(), llfndecl);
1745 Some(_) | None => {}
1749 // Translate a module. Doing this amounts to translating the items in the
1750 // module; there ends up being no artifact (aside from linkage names) of
1751 // separate modules in the compiled program. That's because modules exist
1752 // only as a convenience for humans working with the code, to organize names
1753 // and control visibility.
1754 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1755 let _icx = push_ctxt("trans_mod");
1756 for item in m.items.iter() {
1757 trans_item(ccx, &**item);
1761 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
1763 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1765 if !ccx.reachable.contains(&node_id) {
1766 llvm::SetLinkage(llfn, llvm::InternalLinkage);
1769 // The stack exhaustion lang item shouldn't have a split stack because
1770 // otherwise it would continue to be exhausted (bad), and both it and the
1771 // eh_personality functions need to be externally linkable.
1772 let def = ast_util::local_def(node_id);
1773 if ccx.tcx.lang_items.stack_exhausted() == Some(def) {
1774 unset_split_stack(llfn);
1775 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1777 if ccx.tcx.lang_items.eh_personality() == Some(def) {
1778 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1782 if is_entry_fn(ccx.sess(), node_id) {
1783 create_entry_wrapper(ccx, sp, llfn);
1787 fn register_fn(ccx: &CrateContext,
1790 node_id: ast::NodeId,
1793 match ty::get(node_type).sty {
1794 ty::ty_bare_fn(ref f) => {
1795 assert!(f.abi == Rust);
1797 _ => fail!("expected bare rust fn")
1800 let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
1801 finish_register_fn(ccx, sp, sym, node_id, llfn);
1805 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t) -> Vec<(uint, u64)> {
1806 use middle::ty::{BrAnon, ReLateBound};
1808 let (fn_sig, has_env) = match ty::get(fn_ty).sty {
1809 ty::ty_closure(ref f) => (f.sig.clone(), true),
1810 ty::ty_bare_fn(ref f) => (f.sig.clone(), false),
1811 _ => fail!("expected closure or function.")
1814 // Since index 0 is the return value of the llvm func, we start
1815 // at either 1 or 2 depending on whether there's an env slot or not
1816 let mut first_arg_offset = if has_env { 2 } else { 1 };
1817 let mut attrs = Vec::new();
1818 let ret_ty = fn_sig.output;
1820 // A function pointer is called without the declaration
1821 // available, so we have to apply any attributes with ABI
1822 // implications directly to the call instruction. Right now,
1823 // the only attribute we need to worry about is `sret`.
1824 if type_of::return_uses_outptr(ccx, ret_ty) {
1825 attrs.push((1, llvm::StructRetAttribute as u64));
1827 // The outptr can be noalias and nocapture because it's entirely
1828 // invisible to the program. We can also mark it as nonnull
1829 attrs.push((1, llvm::NoAliasAttribute as u64));
1830 attrs.push((1, llvm::NoCaptureAttribute as u64));
1831 attrs.push((1, llvm::NonNullAttribute as u64));
1833 // Add one more since there's an outptr
1834 first_arg_offset += 1;
1836 // The `noalias` attribute on the return value is useful to a
1837 // function ptr caller.
1838 match ty::get(ret_ty).sty {
1839 // `~` pointer return values never alias because ownership
1841 ty::ty_uniq(it) if match ty::get(it).sty {
1842 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
1845 attrs.push((llvm::ReturnIndex as uint, llvm::NoAliasAttribute as u64));
1850 // We can also mark the return value as `nonnull` in certain cases
1851 match ty::get(ret_ty).sty {
1852 // These are not really pointers but pairs, (pointer, len)
1854 ty::ty_rptr(_, ty::mt { ty: it, .. }) if match ty::get(it).sty {
1855 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
1857 ty::ty_uniq(_) | ty::ty_rptr(_, _) => {
1858 attrs.push((llvm::ReturnIndex as uint, llvm::NonNullAttribute as u64));
1863 match ty::get(ret_ty).sty {
1865 attrs.push((llvm::ReturnIndex as uint, llvm::ZExtAttribute as u64));
1871 for (idx, &t) in fn_sig.inputs.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
1872 match ty::get(t).sty {
1873 // this needs to be first to prevent fat pointers from falling through
1874 _ if !type_is_immediate(ccx, t) => {
1875 // For non-immediate arguments the callee gets its own copy of
1876 // the value on the stack, so there are no aliases. It's also
1877 // program-invisible so can't possibly capture
1878 attrs.push((idx, llvm::NoAliasAttribute as u64));
1879 attrs.push((idx, llvm::NoCaptureAttribute as u64));
1880 attrs.push((idx, llvm::NonNullAttribute as u64));
1883 attrs.push((idx, llvm::ZExtAttribute as u64));
1885 // `~` pointer parameters never alias because ownership is transferred
1887 attrs.push((idx, llvm::NoAliasAttribute as u64));
1888 attrs.push((idx, llvm::NonNullAttribute as u64));
1890 // `&mut` pointer parameters never alias other parameters, or mutable global data
1891 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable => {
1892 attrs.push((idx, llvm::NoAliasAttribute as u64));
1893 attrs.push((idx, llvm::NonNullAttribute as u64));
1895 ReLateBound(_, BrAnon(_)) => {
1896 attrs.push((idx, llvm::NoCaptureAttribute as u64));
1901 // When a reference in an argument has no named lifetime, it's impossible for that
1902 // reference to escape this function (returned or stored beyond the call by a closure).
1903 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
1904 attrs.push((idx, llvm::NoCaptureAttribute as u64));
1905 attrs.push((idx, llvm::NonNullAttribute as u64));
1907 // & pointer parameters are never null
1908 ty::ty_rptr(_, _) => {
1909 attrs.push((idx, llvm::NonNullAttribute as u64));
1918 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1919 pub fn register_fn_llvmty(ccx: &CrateContext,
1922 node_id: ast::NodeId,
1924 llfty: Type) -> ValueRef {
1925 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1927 let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
1928 finish_register_fn(ccx, sp, sym, node_id, llfn);
1932 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1933 match *sess.entry_fn.borrow() {
1934 Some((entry_id, _)) => node_id == entry_id,
1939 // Create a _rust_main(args: ~[str]) function which will be called from the
1940 // runtime rust_start function
1941 pub fn create_entry_wrapper(ccx: &CrateContext,
1943 main_llfn: ValueRef) {
1944 let et = ccx.sess().entry_type.get().unwrap();
1946 config::EntryMain => {
1947 create_entry_fn(ccx, main_llfn, true);
1949 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
1950 config::EntryNone => {} // Do nothing.
1953 fn create_entry_fn(ccx: &CrateContext,
1954 rust_main: ValueRef,
1955 use_start_lang_item: bool) {
1956 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1959 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
1960 let llbb = "top".with_c_str(|buf| {
1962 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1965 let bld = ccx.builder.b;
1967 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1969 let (start_fn, args) = if use_start_lang_item {
1970 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1972 Err(s) => { ccx.sess().fatal(s.as_slice()); }
1974 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1975 get_item_val(ccx, start_def_id.node)
1977 let start_fn_type = csearch::get_type(ccx.tcx(),
1979 trans_external_path(ccx, start_def_id, start_fn_type)
1983 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1984 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1989 llvm::LLVMGetParam(llfn, 0),
1990 llvm::LLVMGetParam(llfn, 1)
1995 debug!("using user-defined start fn");
1997 llvm::LLVMGetParam(llfn, 0 as c_uint),
1998 llvm::LLVMGetParam(llfn, 1 as c_uint)
2004 let result = llvm::LLVMBuildCall(bld,
2007 args.len() as c_uint,
2010 llvm::LLVMBuildRet(bld, result);
2015 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2016 ty: ty::t, attrs: &[ast::Attribute]) -> String {
2017 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2018 // Use provided name
2019 Some(name) => name.get().to_string(),
2021 _ => ccx.tcx.map.with_path(id, |mut path| {
2022 if attr::contains_name(attrs, "no_mangle") {
2024 path.last().unwrap().to_string()
2026 match weak_lang_items::link_name(attrs) {
2027 Some(name) => name.get().to_string(),
2029 // Usual name mangling
2030 mangle_exported_name(ccx, path, ty, id)
2038 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2039 debug!("get_item_val(id=`{:?}`)", id);
2041 match ccx.item_vals.borrow().find_copy(&id) {
2042 Some(v) => return v,
2046 let mut foreign = false;
2047 let item = ccx.tcx.map.get(id);
2048 let val = match item {
2049 ast_map::NodeItem(i) => {
2050 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2051 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2053 let v = match i.node {
2054 ast::ItemStatic(_, mutbl, ref expr) => {
2055 // If this static came from an external crate, then
2056 // we need to get the symbol from csearch instead of
2057 // using the current crate's name/version
2058 // information in the hash of the symbol
2059 debug!("making {}", sym);
2060 let (sym, is_local) = {
2061 match ccx.external_srcs.borrow().find(&i.id) {
2063 debug!("but found in other crate...");
2064 (csearch::get_symbol(&ccx.sess().cstore,
2071 // We need the translated value here, because for enums the
2072 // LLVM type is not fully determined by the Rust type.
2073 let (v, inlineable) = consts::const_expr(ccx, &**expr, is_local);
2074 ccx.const_values.borrow_mut().insert(id, v);
2075 let mut inlineable = inlineable;
2078 let llty = llvm::LLVMTypeOf(v);
2079 let g = sym.as_slice().with_c_str(|buf| {
2080 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2083 if !ccx.reachable.contains(&id) {
2084 llvm::SetLinkage(g, llvm::InternalLinkage);
2087 // Apply the `unnamed_addr` attribute if
2089 if !ast_util::static_has_significant_address(
2091 i.attrs.as_slice()) {
2092 llvm::SetUnnamedAddr(g, true);
2094 // This is a curious case where we must make
2095 // all of these statics inlineable. If a
2096 // global is not tagged as `#[inline(never)]`,
2097 // then LLVM won't coalesce globals unless they
2098 // have an internal linkage type. This means that
2099 // external crates cannot use this global.
2100 // This is a problem for things like inner
2101 // statics in generic functions, because the
2102 // function will be inlined into another
2103 // crate and then attempt to link to the
2104 // static in the original crate, only to
2105 // find that it's not there. On the other
2106 // side of inlining, the crates knows to
2107 // not declare this static as
2108 // available_externally (because it isn't)
2112 if attr::contains_name(i.attrs.as_slice(),
2114 llvm::set_thread_local(g, true);
2118 debug!("{} not inlined", sym);
2119 ccx.non_inlineable_statics.borrow_mut()
2123 ccx.item_symbols.borrow_mut().insert(i.id, sym);
2128 ast::ItemFn(_, _, abi, _, _) => {
2129 let llfn = if abi == Rust {
2130 register_fn(ccx, i.span, sym, i.id, ty)
2132 foreign::register_rust_fn_with_foreign_abi(ccx,
2137 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2141 _ => fail!("get_item_val: weird result in table")
2144 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2146 Some(sect) => unsafe {
2147 sect.get().with_c_str(|buf| {
2148 llvm::LLVMSetSection(v, buf);
2157 ast_map::NodeTraitMethod(trait_method) => {
2158 debug!("get_item_val(): processing a NodeTraitMethod");
2159 match *trait_method {
2160 ast::Required(_) => {
2161 ccx.sess().bug("unexpected variant: required trait method in \
2164 ast::Provided(m) => {
2165 register_method(ccx, id, &*m)
2170 ast_map::NodeMethod(m) => {
2171 register_method(ccx, id, &*m)
2174 ast_map::NodeForeignItem(ni) => {
2178 ast::ForeignItemFn(..) => {
2179 let abi = ccx.tcx.map.get_foreign_abi(id);
2180 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2181 let name = foreign::link_name(&*ni);
2182 foreign::register_foreign_item_fn(ccx, abi, ty,
2183 name.get().as_slice(),
2186 ast::ForeignItemStatic(..) => {
2187 foreign::register_static(ccx, &*ni)
2192 ast_map::NodeVariant(ref v) => {
2194 let args = match v.node.kind {
2195 ast::TupleVariantKind(ref args) => args,
2196 ast::StructVariantKind(_) => {
2197 fail!("struct variant kind unexpected in get_item_val")
2200 assert!(args.len() != 0u);
2201 let ty = ty::node_id_to_type(ccx.tcx(), id);
2202 let parent = ccx.tcx.map.get_parent(id);
2203 let enm = ccx.tcx.map.expect_item(parent);
2204 let sym = exported_name(ccx,
2207 enm.attrs.as_slice());
2209 llfn = match enm.node {
2210 ast::ItemEnum(_, _) => {
2211 register_fn(ccx, (*v).span, sym, id, ty)
2213 _ => fail!("NodeVariant, shouldn't happen")
2215 set_inline_hint(llfn);
2219 ast_map::NodeStructCtor(struct_def) => {
2220 // Only register the constructor if this is a tuple-like struct.
2221 let ctor_id = match struct_def.ctor_id {
2223 ccx.sess().bug("attempt to register a constructor of \
2224 a non-tuple-like struct")
2226 Some(ctor_id) => ctor_id,
2228 let parent = ccx.tcx.map.get_parent(id);
2229 let struct_item = ccx.tcx.map.expect_item(parent);
2230 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2231 let sym = exported_name(ccx,
2236 let llfn = register_fn(ccx, struct_item.span,
2238 set_inline_hint(llfn);
2243 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2244 variant).as_slice())
2248 // foreign items (extern fns and extern statics) don't have internal
2249 // linkage b/c that doesn't quite make sense. Otherwise items can
2250 // have internal linkage if they're not reachable.
2251 if !foreign && !ccx.reachable.contains(&id) {
2252 llvm::SetLinkage(val, llvm::InternalLinkage);
2255 ccx.item_vals.borrow_mut().insert(id, val);
2259 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2260 m: &ast::Method) -> ValueRef {
2261 let mty = ty::node_id_to_type(ccx.tcx(), id);
2263 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2265 let llfn = register_fn(ccx, m.span, sym, id, mty);
2266 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2270 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2272 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2276 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2277 -> encoder::EncodeParams<'r> {
2278 encoder::EncodeParams {
2279 diag: cx.sess().diagnostic(),
2281 reexports2: &cx.exp_map2,
2282 item_symbols: &cx.item_symbols,
2283 non_inlineable_statics: &cx.non_inlineable_statics,
2284 link_meta: &cx.link_meta,
2285 cstore: &cx.sess().cstore,
2286 encode_inlined_item: ie,
2287 reachable: &cx.reachable,
2291 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2294 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2295 *ty != config::CrateTypeExecutable
2301 let encode_inlined_item: encoder::EncodeInlinedItem =
2302 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2304 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2305 let metadata = encoder::encode_metadata(encode_parms, krate);
2306 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2307 .append(match flate::deflate_bytes(metadata.as_slice()) {
2308 Some(compressed) => compressed,
2310 cx.sess().fatal("failed to compress metadata")
2313 let llmeta = C_bytes(cx, compressed.as_slice());
2314 let llconst = C_struct(cx, [llmeta], false);
2315 let name = format!("rust_metadata_{}_{}",
2316 cx.link_meta.crate_name,
2317 cx.link_meta.crate_hash);
2318 let llglobal = name.with_c_str(|buf| {
2320 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2324 llvm::LLVMSetInitializer(llglobal, llconst);
2325 let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2326 name.unwrap_or("rust_metadata").with_c_str(|buf| {
2327 llvm::LLVMSetSection(llglobal, buf)
2333 pub fn trans_crate(krate: ast::Crate,
2334 analysis: CrateAnalysis) -> (ty::ctxt, CrateTranslation) {
2335 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
2337 // Before we touch LLVM, make sure that multithreading is enabled.
2339 use std::sync::{Once, ONCE_INIT};
2340 static mut INIT: Once = ONCE_INIT;
2341 static mut POISONED: bool = false;
2343 if llvm::LLVMStartMultithreaded() != 1 {
2344 // use an extra bool to make sure that all future usage of LLVM
2345 // cannot proceed despite the Once not running more than once.
2351 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2355 let link_meta = link::build_link_meta(&tcx.sess, &krate, name);
2357 // Append ".rs" to crate name as LLVM module identifier.
2359 // LLVM code generator emits a ".file filename" directive
2360 // for ELF backends. Value of the "filename" is set as the
2361 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2362 // crashes if the module identifier is same as other symbols
2363 // such as a function name in the module.
2364 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2365 let mut llmod_id = link_meta.crate_name.clone();
2366 llmod_id.push_str(".rs");
2368 let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2369 Sha256::new(), link_meta, reachable);
2371 // First, verify intrinsics.
2372 intrinsic::check_intrinsics(&ccx);
2374 // Next, translate the module.
2376 let _icx = push_ctxt("text");
2377 trans_mod(&ccx, &krate.module);
2380 glue::emit_tydescs(&ccx);
2381 if ccx.sess().opts.debuginfo != NoDebugInfo {
2382 debuginfo::finalize(&ccx);
2385 // Translate the metadata.
2386 let metadata = write_metadata(&ccx, &krate);
2387 if ccx.sess().trans_stats() {
2388 println!("--- trans stats ---");
2389 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2390 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2391 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2392 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2394 println!("n_fns: {}", ccx.stats.n_fns.get());
2395 println!("n_monos: {}", ccx.stats.n_monos.get());
2396 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2397 println!("n_closures: {}", ccx.stats.n_closures.get());
2398 println!("fn stats:");
2399 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2400 insns_b.cmp(&insns_a)
2402 for tuple in ccx.stats.fn_stats.borrow().iter() {
2404 (ref name, ms, insns) => {
2405 println!("{} insns, {} ms, {}", insns, ms, *name);
2410 if ccx.sess().count_llvm_insns() {
2411 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2412 println!("{:7u} {}", *v, *k);
2416 let llcx = ccx.llcx;
2417 let link_meta = ccx.link_meta.clone();
2418 let llmod = ccx.llmod;
2420 let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
2421 ccx.item_symbols.borrow().find(id).map(|s| s.to_string())
2424 // For the purposes of LTO, we add to the reachable set all of the upstream
2425 // reachable extern fns. These functions are all part of the public ABI of
2426 // the final product, so LTO needs to preserve them.
2427 ccx.sess().cstore.iter_crate_data(|cnum, _| {
2428 let syms = csearch::get_reachable_extern_fns(&ccx.sess().cstore, cnum);
2429 reachable.extend(syms.move_iter().map(|did| {
2430 csearch::get_symbol(&ccx.sess().cstore, did)
2434 // Make sure that some other crucial symbols are not eliminated from the
2435 // module. This includes the main function, the crate map (used for debug
2436 // log settings and I/O), and finally the curious rust_stack_exhausted
2437 // symbol. This symbol is required for use by the libmorestack library that
2438 // we link in, so we must ensure that this symbol is not internalized (if
2439 // defined in the crate).
2440 reachable.push("main".to_string());
2441 reachable.push("rust_stack_exhausted".to_string());
2443 // referenced from .eh_frame section on some platforms
2444 reachable.push("rust_eh_personality".to_string());
2445 // referenced from rt/rust_try.ll
2446 reachable.push("rust_eh_personality_catch".to_string());
2448 let metadata_module = ccx.metadata_llmod;
2449 let formats = ccx.tcx.dependency_formats.borrow().clone();
2450 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
2452 (ccx.tcx, CrateTranslation {
2456 metadata_module: metadata_module,
2458 reachable: reachable,
2459 crate_formats: formats,
2460 no_builtins: no_builtins,