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::OutputFilenames;
34 use driver::driver::{CrateAnalysis, CrateTranslation};
35 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
36 use lib::llvm::{llvm, Vector};
38 use metadata::{csearch, encoder, loader};
40 use middle::astencode;
41 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
42 use middle::weak_lang_items;
44 use middle::subst::Subst;
45 use middle::trans::_match;
46 use middle::trans::adt;
47 use middle::trans::build::*;
48 use middle::trans::builder::{Builder, noname};
49 use middle::trans::callee;
50 use middle::trans::cleanup;
51 use middle::trans::cleanup::CleanupMethods;
52 use middle::trans::common::*;
53 use middle::trans::consts;
54 use middle::trans::controlflow;
55 use middle::trans::datum;
56 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
57 use middle::trans::debuginfo;
58 use middle::trans::expr;
59 use middle::trans::foreign;
60 use middle::trans::glue;
61 use middle::trans::inline;
62 use middle::trans::intrinsic;
63 use middle::trans::machine;
64 use middle::trans::machine::{llalign_of_min, llsize_of, llsize_of_real};
65 use middle::trans::meth;
66 use middle::trans::monomorphize;
67 use middle::trans::tvec;
68 use middle::trans::type_::Type;
69 use middle::trans::type_of;
70 use middle::trans::type_of::*;
71 use middle::trans::value::Value;
74 use util::common::indenter;
75 use util::ppaux::{Repr, ty_to_str};
76 use util::sha2::Sha256;
77 use util::nodemap::NodeMap;
79 use arena::TypedArena;
80 use libc::{c_uint, uint64_t};
81 use std::c_str::ToCStr;
82 use std::cell::{Cell, RefCell};
84 use std::{i8, i16, i32, i64};
86 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
87 use syntax::ast_util::{local_def, is_local};
88 use syntax::attr::AttrMetaMethods;
90 use syntax::codemap::Span;
91 use syntax::parse::token::InternedString;
92 use syntax::visit::Visitor;
94 use syntax::{ast, ast_util, ast_map};
98 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
100 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
101 match task_local_insn_key.get() {
102 Some(ctx) => blk(ctx.borrow().as_slice()),
107 pub fn init_insn_ctxt() {
108 task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
111 pub struct _InsnCtxt {
112 _cannot_construct_outside_of_this_module: ()
116 impl Drop for _InsnCtxt {
118 match task_local_insn_key.get() {
119 Some(ctx) => { ctx.borrow_mut().pop(); }
125 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
126 debug!("new InsnCtxt: {}", s);
127 match task_local_insn_key.get() {
128 Some(ctx) => ctx.borrow_mut().push(s),
131 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
134 pub struct StatRecorder<'a> {
135 ccx: &'a CrateContext,
136 name: Option<String>,
141 impl<'a> StatRecorder<'a> {
142 pub fn new(ccx: &'a CrateContext, name: String) -> StatRecorder<'a> {
143 let start = if ccx.sess().trans_stats() {
144 time::precise_time_ns()
148 let istart = ccx.stats.n_llvm_insns.get();
159 impl<'a> Drop for StatRecorder<'a> {
161 if self.ccx.sess().trans_stats() {
162 let end = time::precise_time_ns();
163 let elapsed = ((end - self.start) / 1_000_000) as uint;
164 let iend = self.ccx.stats.n_llvm_insns.get();
165 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
167 iend - self.istart));
168 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
169 // Reset LLVM insn count to avoid compound costs.
170 self.ccx.stats.n_llvm_insns.set(self.istart);
175 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
176 fn decl_fn(ccx: &CrateContext, name: &str, cc: lib::llvm::CallConv,
177 ty: Type, output: ty::t) -> ValueRef {
179 let llfn: ValueRef = name.with_c_str(|buf| {
181 llvm::LLVMGetOrInsertFunction(ccx.llmod, buf, ty.to_ref())
185 match ty::get(output).sty {
186 // functions returning bottom may unwind, but can never return normally
189 llvm::LLVMAddFunctionAttribute(llfn,
190 lib::llvm::FunctionIndex as c_uint,
191 lib::llvm::NoReturnAttribute as uint64_t)
197 lib::llvm::SetFunctionCallConv(llfn, cc);
198 // Function addresses in Rust are never significant, allowing functions to be merged.
199 lib::llvm::SetUnnamedAddr(llfn, true);
201 if ccx.is_split_stack_supported() {
202 set_split_stack(llfn);
208 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
209 pub fn decl_cdecl_fn(ccx: &CrateContext,
212 output: ty::t) -> ValueRef {
213 decl_fn(ccx, name, lib::llvm::CCallConv, ty, output)
216 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
217 pub fn get_extern_fn(ccx: &CrateContext,
218 externs: &mut ExternMap,
220 cc: lib::llvm::CallConv,
224 match externs.find_equiv(&name) {
225 Some(n) => return *n,
228 let f = decl_fn(ccx, name, cc, ty, output);
229 externs.insert(name.to_string(), f);
233 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
234 match ccx.externs.borrow().find_equiv(&name) {
235 Some(n) => return *n,
239 let f = decl_rust_fn(ccx, fn_ty, name);
241 csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
242 set_llvm_fn_attrs(attrs.as_slice(), f)
245 ccx.externs.borrow_mut().insert(name.to_string(), f);
249 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
250 let (inputs, output, has_env) = match ty::get(fn_ty).sty {
251 ty::ty_bare_fn(ref f) => (f.sig.inputs.clone(), f.sig.output, false),
252 ty::ty_closure(ref f) => (f.sig.inputs.clone(), f.sig.output, true),
253 _ => fail!("expected closure or fn")
256 let llfty = type_of_rust_fn(ccx, has_env, inputs.as_slice(), output);
257 let llfn = decl_fn(ccx, name, lib::llvm::CCallConv, llfty, output);
258 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
259 for &(idx, attr) in attrs.iter() {
261 llvm::LLVMAddFunctionAttribute(llfn, idx as c_uint, attr);
268 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
269 let llfn = decl_rust_fn(ccx, fn_ty, name);
270 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
274 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
275 name: &str, ty: Type) -> ValueRef {
276 match externs.find_equiv(&name) {
277 Some(n) => return *n,
281 let c = name.with_c_str(|buf| {
282 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
284 externs.insert(name.to_string(), c);
289 // Returns a pointer to the body for the box. The box may be an opaque
290 // box. The result will be casted to the type of body_t, if it is statically
292 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
293 let _icx = push_ctxt("at_box_body");
295 let ty = Type::at_box(ccx, type_of(ccx, body_t));
296 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
297 GEPi(bcx, boxptr, [0u, abi::box_field_body])
300 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
301 match bcx.tcx().lang_items.require(it) {
304 bcx.sess().fatal(format!("allocation of `{}` {}",
305 bcx.ty_to_str(info_ty),
311 // The following malloc_raw_dyn* functions allocate a box to contain
312 // a given type, but with a potentially dynamic size.
314 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
319 let _icx = push_ctxt("malloc_raw_exchange");
323 let r = callee::trans_lang_call(bcx,
324 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
328 let llty_ptr = type_of::type_of(ccx, ptr_ty);
329 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
332 pub fn malloc_raw_dyn_managed<'a>(
338 let _icx = push_ctxt("malloc_raw_managed");
341 let langcall = require_alloc_fn(bcx, t, alloc_fn);
343 // Grab the TypeRef type of box_ptr_ty.
344 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
345 let llty = type_of(ccx, box_ptr_ty);
346 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
349 let drop_glue = glue::get_drop_glue(ccx, t);
350 let r = callee::trans_lang_call(
354 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
359 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
362 // Type descriptor and type glue stuff
364 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
365 match ccx.tydescs.borrow().find(&t) {
366 Some(inf) => return inf.clone(),
370 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
371 let inf = Rc::new(glue::declare_tydesc(ccx, t));
373 ccx.tydescs.borrow_mut().insert(t, inf.clone());
377 #[allow(dead_code)] // useful
378 pub fn set_optimize_for_size(f: ValueRef) {
379 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
382 pub fn set_no_inline(f: ValueRef) {
383 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
386 #[allow(dead_code)] // useful
387 pub fn set_no_unwind(f: ValueRef) {
388 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
391 // Tell LLVM to emit the information necessary to unwind the stack for the
393 pub fn set_uwtable(f: ValueRef) {
394 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
397 pub fn set_inline_hint(f: ValueRef) {
398 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
401 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
403 // Set the inline hint if there is one
404 match find_inline_attr(attrs) {
405 InlineHint => set_inline_hint(llfn),
406 InlineAlways => set_always_inline(llfn),
407 InlineNever => set_no_inline(llfn),
408 InlineNone => { /* fallthrough */ }
411 // Add the no-split-stack attribute if requested
412 if contains_name(attrs, "no_split_stack") {
413 unset_split_stack(llfn);
416 if contains_name(attrs, "cold") {
418 llvm::LLVMAddFunctionAttribute(llfn,
419 lib::llvm::FunctionIndex as c_uint,
420 lib::llvm::ColdAttribute as uint64_t)
425 pub fn set_always_inline(f: ValueRef) {
426 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
429 pub fn set_split_stack(f: ValueRef) {
430 "split-stack".with_c_str(|buf| {
431 unsafe { llvm::LLVMAddFunctionAttrString(f, lib::llvm::FunctionIndex as c_uint, buf); }
435 pub fn unset_split_stack(f: ValueRef) {
436 "split-stack".with_c_str(|buf| {
437 unsafe { llvm::LLVMRemoveFunctionAttrString(f, lib::llvm::FunctionIndex as c_uint, buf); }
441 // Double-check that we never ask LLVM to declare the same symbol twice. It
442 // silently mangles such symbols, breaking our linkage model.
443 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
444 if ccx.all_llvm_symbols.borrow().contains(&sym) {
445 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
447 ccx.all_llvm_symbols.borrow_mut().insert(sym);
451 pub fn get_res_dtor(ccx: &CrateContext,
454 parent_id: ast::DefId,
455 substs: &subst::Substs)
457 let _icx = push_ctxt("trans_res_dtor");
458 let did = if did.krate != ast::LOCAL_CRATE {
459 inline::maybe_instantiate_inline(ccx, did)
464 if !substs.types.is_empty() {
465 assert_eq!(did.krate, ast::LOCAL_CRATE);
467 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
468 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
471 } else if did.krate == ast::LOCAL_CRATE {
472 get_item_val(ccx, did.node)
475 let name = csearch::get_symbol(&ccx.sess().cstore, did);
476 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
477 let llty = type_of_dtor(ccx, class_ty);
478 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
479 [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
481 &mut *ccx.externs.borrow_mut(),
483 lib::llvm::CCallConv,
489 // Structural comparison: a rather involved form of glue.
490 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
491 if cx.sess().opts.cg.save_temps {
494 llvm::LLVMSetValueName(v, buf)
501 // Used only for creating scalar comparison glue.
502 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
504 // NB: This produces an i1, not a Rust bool (i8).
505 pub fn compare_scalar_types<'a>(
512 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
514 match ty::get(t).sty {
515 ty::ty_nil => f(nil_type),
516 ty::ty_bool | ty::ty_ptr(_) |
517 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
518 ty::ty_int(_) => f(signed_int),
519 ty::ty_float(_) => f(floating_point),
520 // Should never get here, because t is scalar.
521 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
526 // A helper function to do the actual comparison of scalar values.
527 pub fn compare_scalar_values<'a>(
534 let _icx = push_ctxt("compare_scalar_values");
535 fn die(cx: &Block) -> ! {
536 cx.sess().bug("compare_scalar_values: must be a comparison operator");
540 // We don't need to do actual comparisons for nil.
541 // () == () holds but () < () does not.
543 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(cx.ccx(), true),
544 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(cx.ccx(), false),
545 // refinements would be nice
551 ast::BiEq => lib::llvm::RealOEQ,
552 ast::BiNe => lib::llvm::RealUNE,
553 ast::BiLt => lib::llvm::RealOLT,
554 ast::BiLe => lib::llvm::RealOLE,
555 ast::BiGt => lib::llvm::RealOGT,
556 ast::BiGe => lib::llvm::RealOGE,
559 return FCmp(cx, cmp, lhs, rhs);
563 ast::BiEq => lib::llvm::IntEQ,
564 ast::BiNe => lib::llvm::IntNE,
565 ast::BiLt => lib::llvm::IntSLT,
566 ast::BiLe => lib::llvm::IntSLE,
567 ast::BiGt => lib::llvm::IntSGT,
568 ast::BiGe => lib::llvm::IntSGE,
571 return ICmp(cx, cmp, lhs, rhs);
575 ast::BiEq => lib::llvm::IntEQ,
576 ast::BiNe => lib::llvm::IntNE,
577 ast::BiLt => lib::llvm::IntULT,
578 ast::BiLe => lib::llvm::IntULE,
579 ast::BiGt => lib::llvm::IntUGT,
580 ast::BiGe => lib::llvm::IntUGE,
583 return ICmp(cx, cmp, lhs, rhs);
588 pub fn compare_simd_types(
596 match ty::get(t).sty {
598 // The comparison operators for floating point vectors are challenging.
599 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
600 // then bitcast to a floating point vector, the result will be `-NaN`
601 // for each truth value. Because of this they are unsupported.
602 cx.sess().bug("compare_simd_types: comparison operators \
603 not supported for floating point SIMD types")
605 ty::ty_uint(_) | ty::ty_int(_) => {
607 ast::BiEq => lib::llvm::IntEQ,
608 ast::BiNe => lib::llvm::IntNE,
609 ast::BiLt => lib::llvm::IntSLT,
610 ast::BiLe => lib::llvm::IntSLE,
611 ast::BiGt => lib::llvm::IntSGT,
612 ast::BiGe => lib::llvm::IntSGE,
613 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
615 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
616 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
617 // to get the correctly sized type. This will compile to a single instruction
618 // once the IR is converted to assembly if the SIMD instruction is supported
619 // by the target architecture.
620 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
622 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
626 pub type val_and_ty_fn<'r,'b> =
627 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
629 // Iterates through the elements of a structural type.
630 pub fn iter_structural_ty<'r,
635 f: val_and_ty_fn<'r,'b>)
637 let _icx = push_ctxt("iter_structural_ty");
644 variant: &ty::VariantInfo,
645 substs: &subst::Substs,
646 f: val_and_ty_fn<'r,'b>)
648 let _icx = push_ctxt("iter_variant");
652 for (i, &arg) in variant.args.iter().enumerate() {
654 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
655 arg.subst(tcx, substs));
661 match ty::get(t).sty {
662 ty::ty_struct(..) => {
663 let repr = adt::represent_type(cx.ccx(), t);
664 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
665 for (i, field_ty) in field_tys.iter().enumerate() {
666 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
667 cx = f(cx, llfld_a, field_ty.mt.ty);
671 ty::ty_vec(_, Some(n)) => {
672 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
673 let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
674 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
676 ty::ty_tup(ref args) => {
677 let repr = adt::represent_type(cx.ccx(), t);
678 for (i, arg) in args.iter().enumerate() {
679 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
680 cx = f(cx, llfld_a, *arg);
683 ty::ty_enum(tid, ref substs) => {
687 let repr = adt::represent_type(ccx, t);
688 let variants = ty::enum_variants(ccx.tcx(), tid);
689 let n_variants = (*variants).len();
691 // NB: we must hit the discriminant first so that structural
692 // comparison know not to proceed when the discriminants differ.
694 match adt::trans_switch(cx, &*repr, av) {
695 (_match::single, None) => {
696 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
699 (_match::switch, Some(lldiscrim_a)) => {
700 cx = f(cx, lldiscrim_a, ty::mk_int());
701 let unr_cx = fcx.new_temp_block("enum-iter-unr");
703 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
705 let next_cx = fcx.new_temp_block("enum-iter-next");
707 for variant in (*variants).iter() {
710 format!("enum-iter-variant-{}",
711 variant.disr_val.to_str().as_slice())
713 match adt::trans_case(cx, &*repr, variant.disr_val) {
714 _match::single_result(r) => {
715 AddCase(llswitch, r.val, variant_cx.llbb)
717 _ => ccx.sess().unimpl("value from adt::trans_case \
718 in iter_structural_ty")
721 iter_variant(variant_cx,
727 Br(variant_cx, next_cx.llbb);
731 _ => ccx.sess().unimpl("value from adt::trans_switch \
732 in iter_structural_ty")
735 _ => cx.sess().unimpl("type in iter_structural_ty")
740 pub fn cast_shift_expr_rhs<'a>(
746 cast_shift_rhs(op, lhs, rhs,
747 |a,b| Trunc(cx, a, b),
748 |a,b| ZExt(cx, a, b))
751 pub fn cast_shift_const_rhs(op: ast::BinOp,
752 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
753 cast_shift_rhs(op, lhs, rhs,
754 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
755 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
758 pub fn cast_shift_rhs(op: ast::BinOp,
761 trunc: |ValueRef, Type| -> ValueRef,
762 zext: |ValueRef, Type| -> ValueRef)
764 // Shifts may have any size int on the rhs
766 if ast_util::is_shift_binop(op) {
767 let mut rhs_llty = val_ty(rhs);
768 let mut lhs_llty = val_ty(lhs);
769 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
770 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
771 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
772 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
775 } else if lhs_sz > rhs_sz {
776 // FIXME (#1877: If shifting by negative
777 // values becomes not undefined then this is wrong.
788 pub fn fail_if_zero_or_overflows<'a>(
796 let (zero_text, overflow_text) = if divrem == ast::BiDiv {
797 ("attempted to divide by zero",
798 "attempted to divide with overflow")
800 ("attempted remainder with a divisor of zero",
801 "attempted remainder with overflow")
803 let (is_zero, is_signed) = match ty::get(rhs_t).sty {
805 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
806 (ICmp(cx, lib::llvm::IntEQ, rhs, zero), true)
809 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
810 (ICmp(cx, lib::llvm::IntEQ, rhs, zero), false)
813 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
814 ty_to_str(cx.tcx(), rhs_t)).as_slice());
817 let bcx = with_cond(cx, is_zero, |bcx| {
818 controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
821 // To quote LLVM's documentation for the sdiv instruction:
823 // Division by zero leads to undefined behavior. Overflow also leads
824 // to undefined behavior; this is a rare case, but can occur, for
825 // example, by doing a 32-bit division of -2147483648 by -1.
827 // In order to avoid undefined behavior, we perform runtime checks for
828 // signed division/remainder which would trigger overflow. For unsigned
829 // integers, no action beyond checking for zero need be taken.
831 let (llty, min) = match ty::get(rhs_t).sty {
833 let llty = Type::int_from_ty(cx.ccx(), t);
835 ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
836 ast::TyI => i64::MIN as u64,
837 ast::TyI8 => i8::MIN as u64,
838 ast::TyI16 => i16::MIN as u64,
839 ast::TyI32 => i32::MIN as u64,
840 ast::TyI64 => i64::MIN as u64,
846 let minus_one = ICmp(bcx, lib::llvm::IntEQ, rhs,
847 C_integral(llty, -1, false));
848 with_cond(bcx, minus_one, |bcx| {
849 let is_min = ICmp(bcx, lib::llvm::IntEQ, lhs,
850 C_integral(llty, min, true));
851 with_cond(bcx, is_min, |bcx| {
852 controlflow::trans_fail(bcx, span,
853 InternedString::new(overflow_text))
861 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
862 let name = csearch::get_symbol(&ccx.sess().cstore, did);
863 match ty::get(t).sty {
864 ty::ty_bare_fn(ref fn_ty) => {
865 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
866 ccx.sess().targ_cfg.arch) {
867 Some(Rust) | Some(RustIntrinsic) => {
868 get_extern_rust_fn(ccx, t, name.as_slice(), did)
871 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
872 name.as_slice(), None)
876 ty::ty_closure(_) => {
877 get_extern_rust_fn(ccx, t, name.as_slice(), did)
880 let llty = type_of(ccx, t);
881 get_extern_const(&mut *ccx.externs.borrow_mut(),
892 llargs: Vec<ValueRef> ,
894 call_info: Option<NodeInfo>)
895 -> (ValueRef, &'a Block<'a>) {
896 let _icx = push_ctxt("invoke_");
897 if bcx.unreachable.get() {
898 return (C_null(Type::i8(bcx.ccx())), bcx);
901 let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
903 match bcx.opt_node_id {
905 debug!("invoke at ???");
908 debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
912 if need_invoke(bcx) {
913 debug!("invoking {} at {}", llfn, bcx.llbb);
914 for &llarg in llargs.iter() {
915 debug!("arg: {}", llarg);
917 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
918 let landing_pad = bcx.fcx.get_landing_pad();
921 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
922 None => debuginfo::clear_source_location(bcx.fcx)
925 let llresult = Invoke(bcx,
930 attributes.as_slice());
931 return (llresult, normal_bcx);
933 debug!("calling {} at {}", llfn, bcx.llbb);
934 for &llarg in llargs.iter() {
935 debug!("arg: {}", llarg);
939 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
940 None => debuginfo::clear_source_location(bcx.fcx)
943 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes.as_slice());
944 return (llresult, bcx);
948 pub fn need_invoke(bcx: &Block) -> bool {
949 if bcx.sess().no_landing_pads() {
953 // Avoid using invoke if we are already inside a landing pad.
958 bcx.fcx.needs_invoke()
961 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
962 let _icx = push_ctxt("load_if_immediate");
963 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
967 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
968 match local.pat.node {
969 ast::PatWild => true, _ => false
973 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
975 debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
976 let _indenter = indenter();
977 let _icx = push_ctxt("init_local");
978 _match::store_local(bcx, local)
981 pub fn raw_block<'a>(
982 fcx: &'a FunctionContext<'a>,
986 Block::new(llbb, is_lpad, None, fcx)
989 pub fn with_cond<'a>(
992 f: |&'a Block<'a>| -> &'a Block<'a>)
994 let _icx = push_ctxt("with_cond");
996 let next_cx = fcx.new_temp_block("next");
997 let cond_cx = fcx.new_temp_block("cond");
998 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
999 let after_cx = f(cond_cx);
1000 if !after_cx.terminated.get() {
1001 Br(after_cx, next_cx.llbb);
1006 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1007 let _icx = push_ctxt("call_memcpy");
1009 let key = match ccx.sess().targ_cfg.arch {
1010 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1011 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1013 let memcpy = ccx.get_intrinsic(&key);
1014 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1015 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1016 let size = IntCast(cx, n_bytes, ccx.int_type);
1017 let align = C_i32(ccx, align as i32);
1018 let volatile = C_i1(ccx, false);
1019 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1022 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1023 let _icx = push_ctxt("memcpy_ty");
1024 let ccx = bcx.ccx();
1025 if ty::type_is_structural(t) {
1026 let llty = type_of::type_of(ccx, t);
1027 let llsz = llsize_of(ccx, llty);
1028 let llalign = llalign_of_min(ccx, llty);
1029 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1031 Store(bcx, Load(bcx, src), dst);
1035 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1036 if cx.unreachable.get() { return; }
1037 let _icx = push_ctxt("zero_mem");
1040 let llty = type_of::type_of(ccx, t);
1041 memzero(&B(bcx), llptr, llty);
1044 // Always use this function instead of storing a zero constant to the memory
1045 // in question. If you store a zero constant, LLVM will drown in vreg
1046 // allocation for large data structures, and the generated code will be
1047 // awful. (A telltale sign of this is large quantities of
1048 // `mov [byte ptr foo],0` in the generated code.)
1049 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1050 let _icx = push_ctxt("memzero");
1053 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1054 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1055 X86_64 => "llvm.memset.p0i8.i64"
1058 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1059 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1060 let llzeroval = C_u8(ccx, 0);
1061 let size = machine::llsize_of(ccx, ty);
1062 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1063 let volatile = C_i1(ccx, false);
1064 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1067 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1068 let _icx = push_ctxt("alloc_ty");
1069 let ccx = bcx.ccx();
1070 let ty = type_of::type_of(ccx, t);
1071 assert!(!ty::type_has_params(t));
1072 let val = alloca(bcx, ty, name);
1076 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1077 alloca_maybe_zeroed(cx, ty, name, false)
1080 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1081 let _icx = push_ctxt("alloca");
1082 if cx.unreachable.get() {
1084 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1087 debuginfo::clear_source_location(cx.fcx);
1088 let p = Alloca(cx, ty, name);
1090 let b = cx.fcx.ccx.builder();
1091 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1097 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1098 let _icx = push_ctxt("arrayalloca");
1099 if cx.unreachable.get() {
1101 return llvm::LLVMGetUndef(ty.to_ref());
1104 debuginfo::clear_source_location(cx.fcx);
1105 return ArrayAlloca(cx, ty, v);
1108 // Creates and returns space for, or returns the argument representing, the
1109 // slot where the return value of the function must go.
1110 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1113 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1114 llvm::LLVMGetParam(fcx.llfn, 0)
1116 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1117 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1118 Alloca(bcx, lloutputtype, "__make_return_pointer")
1123 // NB: must keep 4 fns in sync:
1126 // - create_datums_for_fn_args.
1130 // Be warned! You must call `init_function` before doing anything with the
1131 // returned function context.
1132 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1137 param_substs: &'a param_substs,
1139 block_arena: &'a TypedArena<Block<'a>>)
1140 -> FunctionContext<'a> {
1141 param_substs.validate();
1143 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1147 ccx.tcx.map.path_to_str(id).to_string()
1149 id, param_substs.repr(ccx.tcx()));
1151 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1152 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1153 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1155 let mut fcx = FunctionContext {
1158 llretptr: Cell::new(None),
1159 entry_bcx: RefCell::new(None),
1160 alloca_insert_pt: Cell::new(None),
1161 llreturn: Cell::new(None),
1162 personality: Cell::new(None),
1163 caller_expects_out_pointer: uses_outptr,
1164 llargs: RefCell::new(NodeMap::new()),
1165 lllocals: RefCell::new(NodeMap::new()),
1166 llupvars: RefCell::new(NodeMap::new()),
1168 param_substs: param_substs,
1170 block_arena: block_arena,
1172 debug_context: debug_context,
1173 scopes: RefCell::new(Vec::new())
1177 fcx.llenv = Some(unsafe {
1178 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1185 /// Performs setup on a newly created function, creating the entry scope block
1186 /// and allocating space for the return pointer.
1187 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1189 output_type: ty::t) {
1190 let entry_bcx = fcx.new_temp_block("entry-block");
1192 *fcx.entry_bcx.borrow_mut() = Some(entry_bcx);
1194 // Use a dummy instruction as the insertion point for all allocas.
1195 // This is later removed in FunctionContext::cleanup.
1196 fcx.alloca_insert_pt.set(Some(unsafe {
1197 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1198 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1201 // This shouldn't need to recompute the return type,
1202 // as new_fn_ctxt did it already.
1203 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1205 if !return_type_is_void(fcx.ccx, substd_output_type) {
1206 // If the function returns nil/bot, there is no real return
1207 // value, so do not set `llretptr`.
1208 if !skip_retptr || fcx.caller_expects_out_pointer {
1209 // Otherwise, we normally allocate the llretptr, unless we
1210 // have been instructed to skip it for immediate return
1212 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1217 // NB: must keep 4 fns in sync:
1220 // - create_datums_for_fn_args.
1224 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1225 use middle::trans::datum::{ByRef, ByValue};
1228 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1232 // work around bizarre resolve errors
1233 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1234 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1236 // create_datums_for_fn_args: creates rvalue datums for each of the
1237 // incoming function arguments. These will later be stored into
1238 // appropriate lvalue datums.
1239 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1241 -> Vec<RvalueDatum> {
1242 let _icx = push_ctxt("create_datums_for_fn_args");
1244 // Return an array wrapping the ValueRefs that we get from
1245 // llvm::LLVMGetParam for each argument into datums.
1246 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1247 let llarg = unsafe {
1248 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1250 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1254 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1255 arg_scope: cleanup::CustomScopeIndex,
1258 arg_datums: Vec<RvalueDatum> )
1260 debug!("copy_args_to_allocas");
1262 let _icx = push_ctxt("copy_args_to_allocas");
1265 let arg_scope_id = cleanup::CustomScope(arg_scope);
1267 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1268 // For certain mode/type combinations, the raw llarg values are passed
1269 // by value. However, within the fn body itself, we want to always
1270 // have all locals and arguments be by-ref so that we can cancel the
1271 // cleanup and for better interaction with LLVM's debug info. So, if
1272 // the argument would be passed by value, we store it into an alloca.
1273 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1274 // the event it's not truly needed.
1276 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1278 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1279 debuginfo::create_argument_metadata(bcx, &args[i]);
1286 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1287 // and builds the return block.
1288 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1289 last_bcx: &'a Block<'a>) {
1290 let _icx = push_ctxt("finish_fn");
1292 let ret_cx = match fcx.llreturn.get() {
1294 if !last_bcx.terminated.get() {
1295 Br(last_bcx, llreturn);
1297 raw_block(fcx, false, llreturn)
1301 build_return_block(fcx, ret_cx);
1302 debuginfo::clear_source_location(fcx);
1306 // Builds the return block for a function.
1307 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1308 // Return the value if this function immediate; otherwise, return void.
1309 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1310 return RetVoid(ret_cx);
1313 let retptr = Value(fcx.llretptr.get().unwrap());
1314 let retval = match retptr.get_dominating_store(ret_cx) {
1315 // If there's only a single store to the ret slot, we can directly return
1316 // the value that was stored and omit the store and the alloca
1318 let retval = s.get_operand(0).unwrap().get();
1319 s.erase_from_parent();
1321 if retptr.has_no_uses() {
1322 retptr.erase_from_parent();
1327 // Otherwise, load the return value from the ret slot
1328 None => Load(ret_cx, fcx.llretptr.get().unwrap())
1332 Ret(ret_cx, retval);
1335 // trans_closure: Builds an LLVM function out of a source function.
1336 // If the function closes over its environment a closure will be
1338 pub fn trans_closure(ccx: &CrateContext,
1342 param_substs: ¶m_substs,
1344 _attributes: &[ast::Attribute],
1346 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1347 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1349 let _icx = push_ctxt("trans_closure");
1350 set_uwtable(llfndecl);
1352 debug!("trans_closure(..., param_substs={})",
1353 param_substs.repr(ccx.tcx()));
1355 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1356 ty::ty_closure(_) => true,
1360 let arena = TypedArena::new();
1361 let fcx = new_fn_ctxt(ccx,
1369 init_function(&fcx, false, output_type);
1371 // cleanup scope for the incoming arguments
1372 let arg_scope = fcx.push_custom_cleanup_scope();
1374 // Create the first basic block in the function and keep a handle on it to
1375 // pass to finish_fn later.
1376 let bcx_top = fcx.entry_bcx.borrow().clone().unwrap();
1377 let mut bcx = bcx_top;
1378 let block_ty = node_id_type(bcx, body.id);
1380 // Set up arguments to the function.
1381 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1382 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1384 bcx = copy_args_to_allocas(&fcx,
1387 decl.inputs.as_slice(),
1390 bcx = maybe_load_env(bcx);
1392 // Up until here, IR instructions for this function have explicitly not been annotated with
1393 // source code location, so we don't step into call setup code. From here on, source location
1394 // emitting should be enabled.
1395 debuginfo::start_emitting_source_locations(&fcx);
1397 let dest = match fcx.llretptr.get() {
1398 Some(e) => {expr::SaveIn(e)}
1400 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1405 // This call to trans_block is the place where we bridge between
1406 // translation calls that don't have a return value (trans_crate,
1407 // trans_mod, trans_item, et cetera) and those that do
1408 // (trans_block, trans_expr, et cetera).
1409 bcx = controlflow::trans_block(bcx, body, dest);
1411 match fcx.llreturn.get() {
1413 Br(bcx, fcx.return_exit_block());
1414 fcx.pop_custom_cleanup_scope(arg_scope);
1417 // Microoptimization writ large: avoid creating a separate
1418 // llreturn basic block
1419 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1423 // Put return block after all other blocks.
1424 // This somewhat improves single-stepping experience in debugger.
1426 let llreturn = fcx.llreturn.get();
1427 for &llreturn in llreturn.iter() {
1428 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1432 // Insert the mandatory first few basic blocks before lltop.
1433 finish_fn(&fcx, bcx);
1436 // trans_fn: creates an LLVM function corresponding to a source language
1438 pub fn trans_fn(ccx: &CrateContext,
1442 param_substs: ¶m_substs,
1444 attrs: &[ast::Attribute]) {
1445 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id).to_string());
1446 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1447 let _icx = push_ctxt("trans_fn");
1448 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1449 trans_closure(ccx, decl, body, llfndecl,
1450 param_substs, id, attrs, output_type, |bcx| bcx);
1453 pub fn trans_enum_variant(ccx: &CrateContext,
1454 _enum_id: ast::NodeId,
1455 variant: &ast::Variant,
1456 _args: &[ast::VariantArg],
1458 param_substs: ¶m_substs,
1459 llfndecl: ValueRef) {
1460 let _icx = push_ctxt("trans_enum_variant");
1462 trans_enum_variant_or_tuple_like_struct(
1470 pub fn trans_tuple_struct(ccx: &CrateContext,
1471 _fields: &[ast::StructField],
1472 ctor_id: ast::NodeId,
1473 param_substs: ¶m_substs,
1474 llfndecl: ValueRef) {
1475 let _icx = push_ctxt("trans_tuple_struct");
1477 trans_enum_variant_or_tuple_like_struct(
1485 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1486 ctor_id: ast::NodeId,
1488 param_substs: ¶m_substs,
1489 llfndecl: ValueRef) {
1490 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1491 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1493 let result_ty = match ty::get(ctor_ty).sty {
1494 ty::ty_bare_fn(ref bft) => bft.sig.output,
1495 _ => ccx.sess().bug(
1496 format!("trans_enum_variant_or_tuple_like_struct: \
1497 unexpected ctor return type {}",
1498 ty_to_str(ccx.tcx(), ctor_ty)).as_slice())
1501 let arena = TypedArena::new();
1502 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1503 param_substs, None, &arena);
1504 init_function(&fcx, false, result_ty);
1506 let arg_tys = ty::ty_fn_args(ctor_ty);
1508 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1510 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1512 if !type_is_zero_size(fcx.ccx, result_ty) {
1513 let repr = adt::represent_type(ccx, result_ty);
1514 adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1515 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1516 let lldestptr = adt::trans_field_ptr(bcx,
1518 fcx.llretptr.get().unwrap(),
1521 arg_datum.store_to(bcx, lldestptr);
1525 finish_fn(&fcx, bcx);
1528 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1529 sp: Span, id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1531 for variant in enum_definition.variants.iter() {
1532 let disr_val = vi[*i].disr_val;
1535 match variant.node.kind {
1536 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1537 let llfn = get_item_val(ccx, variant.node.id);
1538 trans_enum_variant(ccx, id, &**variant, args.as_slice(),
1539 disr_val, ¶m_substs::empty(), llfn);
1541 ast::TupleVariantKind(_) => {
1544 ast::StructVariantKind(struct_def) => {
1545 trans_struct_def(ccx, struct_def);
1550 enum_variant_size_lint(ccx, enum_definition, sp, id);
1553 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1554 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1556 let (lvl, src) = ccx.tcx.node_lint_levels.borrow()
1557 .find(&(id, lint::VariantSizeDifference))
1558 .map_or((lint::Allow, lint::Default), |&(lvl,src)| (lvl, src));
1560 if lvl != lint::Allow {
1561 let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
1563 adt::General(_, ref variants) => {
1564 for var in variants.iter() {
1566 for field in var.fields.iter().skip(1) {
1567 // skip the discriminant
1568 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1573 _ => { /* its size is either constant or unimportant */ }
1576 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1577 |(l, s, li), (idx, &size)|
1580 } else if size > s {
1587 // we only warn if the largest variant is at least thrice as large as
1588 // the second-largest.
1589 if largest > slargest * 3 && slargest > 0 {
1590 lint::emit_lint(lvl, src,
1591 format!("enum variant is more than three times larger \
1592 ({} bytes) than the next largest (ignoring padding)",
1593 largest).as_slice(),
1594 sp, lint::lint_to_str(lint::VariantSizeDifference), ccx.tcx());
1596 ccx.sess().span_note(enum_def.variants.get(largest_index).span,
1597 "this variant is the largest");
1602 pub struct TransItemVisitor<'a> {
1603 pub ccx: &'a CrateContext,
1606 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1607 fn visit_item(&mut self, i: &ast::Item, _:()) {
1608 trans_item(self.ccx, i);
1612 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1613 let _icx = push_ctxt("trans_item");
1615 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1617 let llfndecl = get_item_val(ccx, item.id);
1618 foreign::trans_rust_fn_with_foreign_abi(
1619 ccx, &**decl, &**body, item.attrs.as_slice(), llfndecl, item.id);
1620 } else if !generics.is_type_parameterized() {
1621 let llfn = get_item_val(ccx, item.id);
1626 ¶m_substs::empty(),
1628 item.attrs.as_slice());
1630 // Be sure to travel more than just one layer deep to catch nested
1631 // items in blocks and such.
1632 let mut v = TransItemVisitor{ ccx: ccx };
1633 v.visit_block(&**body, ());
1636 ast::ItemImpl(ref generics, _, _, ref ms) => {
1637 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1639 ast::ItemMod(ref m) => {
1642 ast::ItemEnum(ref enum_definition, ref generics) => {
1643 if !generics.is_type_parameterized() {
1644 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1646 trans_enum_def(ccx, enum_definition, item.span, item.id, vi.as_slice(), &mut i);
1649 ast::ItemStatic(_, m, ref expr) => {
1650 // Recurse on the expression to catch items in blocks
1651 let mut v = TransItemVisitor{ ccx: ccx };
1652 v.visit_expr(&**expr, ());
1653 consts::trans_const(ccx, m, item.id);
1654 // Do static_assert checking. It can't really be done much earlier
1655 // because we need to get the value of the bool out of LLVM
1656 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1657 if m == ast::MutMutable {
1658 ccx.sess().span_fatal(expr.span,
1659 "cannot have static_assert on a mutable \
1663 let v = ccx.const_values.borrow().get_copy(&item.id);
1665 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1666 ccx.sess().span_fatal(expr.span, "static assertion failed");
1671 ast::ItemForeignMod(ref foreign_mod) => {
1672 foreign::trans_foreign_mod(ccx, foreign_mod);
1674 ast::ItemStruct(struct_def, ref generics) => {
1675 if !generics.is_type_parameterized() {
1676 trans_struct_def(ccx, struct_def);
1679 ast::ItemTrait(..) => {
1680 // Inside of this trait definition, we won't be actually translating any
1681 // functions, but the trait still needs to be walked. Otherwise default
1682 // methods with items will not get translated and will cause ICE's when
1683 // metadata time comes around.
1684 let mut v = TransItemVisitor{ ccx: ccx };
1685 visit::walk_item(&mut v, item, ());
1687 _ => {/* fall through */ }
1691 pub fn trans_struct_def(ccx: &CrateContext, struct_def: Gc<ast::StructDef>) {
1692 // If this is a tuple-like struct, translate the constructor.
1693 match struct_def.ctor_id {
1694 // We only need to translate a constructor if there are fields;
1695 // otherwise this is a unit-like struct.
1696 Some(ctor_id) if struct_def.fields.len() > 0 => {
1697 let llfndecl = get_item_val(ccx, ctor_id);
1698 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1699 ctor_id, ¶m_substs::empty(), llfndecl);
1701 Some(_) | None => {}
1705 // Translate a module. Doing this amounts to translating the items in the
1706 // module; there ends up being no artifact (aside from linkage names) of
1707 // separate modules in the compiled program. That's because modules exist
1708 // only as a convenience for humans working with the code, to organize names
1709 // and control visibility.
1710 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1711 let _icx = push_ctxt("trans_mod");
1712 for item in m.items.iter() {
1713 trans_item(ccx, &**item);
1717 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
1719 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1721 if !ccx.reachable.contains(&node_id) {
1722 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1725 // The stack exhaustion lang item shouldn't have a split stack because
1726 // otherwise it would continue to be exhausted (bad), and both it and the
1727 // eh_personality functions need to be externally linkable.
1728 let def = ast_util::local_def(node_id);
1729 if ccx.tcx.lang_items.stack_exhausted() == Some(def) {
1730 unset_split_stack(llfn);
1731 lib::llvm::SetLinkage(llfn, lib::llvm::ExternalLinkage);
1733 if ccx.tcx.lang_items.eh_personality() == Some(def) {
1734 lib::llvm::SetLinkage(llfn, lib::llvm::ExternalLinkage);
1738 if is_entry_fn(ccx.sess(), node_id) {
1739 create_entry_wrapper(ccx, sp, llfn);
1743 fn register_fn(ccx: &CrateContext,
1746 node_id: ast::NodeId,
1749 match ty::get(node_type).sty {
1750 ty::ty_bare_fn(ref f) => {
1751 assert!(f.abi == Rust || f.abi == RustIntrinsic);
1753 _ => fail!("expected bare rust fn or an intrinsic")
1756 let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
1757 finish_register_fn(ccx, sp, sym, node_id, llfn);
1761 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t) -> Vec<(uint, u64)> {
1762 use middle::ty::{BrAnon, ReLateBound};
1764 let (fn_sig, has_env) = match ty::get(fn_ty).sty {
1765 ty::ty_closure(ref f) => (f.sig.clone(), true),
1766 ty::ty_bare_fn(ref f) => (f.sig.clone(), false),
1767 _ => fail!("expected closure or function.")
1770 // Since index 0 is the return value of the llvm func, we start
1771 // at either 1 or 2 depending on whether there's an env slot or not
1772 let mut first_arg_offset = if has_env { 2 } else { 1 };
1773 let mut attrs = Vec::new();
1774 let ret_ty = fn_sig.output;
1776 // A function pointer is called without the declaration
1777 // available, so we have to apply any attributes with ABI
1778 // implications directly to the call instruction. Right now,
1779 // the only attribute we need to worry about is `sret`.
1780 if type_of::return_uses_outptr(ccx, ret_ty) {
1781 attrs.push((1, lib::llvm::StructRetAttribute as u64));
1783 // The outptr can be noalias and nocapture because it's entirely
1784 // invisible to the program. We can also mark it as nonnull
1785 attrs.push((1, lib::llvm::NoAliasAttribute as u64));
1786 attrs.push((1, lib::llvm::NoCaptureAttribute as u64));
1787 attrs.push((1, lib::llvm::NonNullAttribute as u64));
1789 // Add one more since there's an outptr
1790 first_arg_offset += 1;
1792 // The `noalias` attribute on the return value is useful to a
1793 // function ptr caller.
1794 match ty::get(ret_ty).sty {
1795 // `~` pointer return values never alias because ownership
1797 ty::ty_uniq(it) if match ty::get(it).sty {
1798 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
1801 attrs.push((lib::llvm::ReturnIndex as uint, lib::llvm::NoAliasAttribute as u64));
1806 // We can also mark the return value as `nonnull` in certain cases
1807 match ty::get(ret_ty).sty {
1808 // These are not really pointers but pairs, (pointer, len)
1810 ty::ty_rptr(_, ty::mt { ty: it, .. }) if match ty::get(it).sty {
1811 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
1813 ty::ty_uniq(_) | ty::ty_rptr(_, _) => {
1814 attrs.push((lib::llvm::ReturnIndex as uint, lib::llvm::NonNullAttribute as u64));
1820 for (idx, &t) in fn_sig.inputs.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
1821 match ty::get(t).sty {
1822 // this needs to be first to prevent fat pointers from falling through
1823 _ if !type_is_immediate(ccx, t) => {
1824 // For non-immediate arguments the callee gets its own copy of
1825 // the value on the stack, so there are no aliases. It's also
1826 // program-invisible so can't possibly capture
1827 attrs.push((idx, lib::llvm::NoAliasAttribute as u64));
1828 attrs.push((idx, lib::llvm::NoCaptureAttribute as u64));
1829 attrs.push((idx, lib::llvm::NonNullAttribute as u64));
1831 // `~` pointer parameters never alias because ownership is transferred
1833 attrs.push((idx, lib::llvm::NoAliasAttribute as u64));
1834 attrs.push((idx, lib::llvm::NonNullAttribute as u64));
1836 // `&mut` pointer parameters never alias other parameters, or mutable global data
1837 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable => {
1838 attrs.push((idx, lib::llvm::NoAliasAttribute as u64));
1839 attrs.push((idx, lib::llvm::NonNullAttribute as u64));
1841 ReLateBound(_, BrAnon(_)) => {
1842 attrs.push((idx, lib::llvm::NoCaptureAttribute as u64));
1847 // When a reference in an argument has no named lifetime, it's impossible for that
1848 // reference to escape this function (returned or stored beyond the call by a closure).
1849 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
1850 attrs.push((idx, lib::llvm::NoCaptureAttribute as u64));
1851 attrs.push((idx, lib::llvm::NonNullAttribute as u64));
1853 // & pointer parameters are never null
1854 ty::ty_rptr(_, _) => {
1855 attrs.push((idx, lib::llvm::NonNullAttribute as u64));
1864 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1865 pub fn register_fn_llvmty(ccx: &CrateContext,
1868 node_id: ast::NodeId,
1869 cc: lib::llvm::CallConv,
1870 llfty: Type) -> ValueRef {
1871 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1873 let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
1874 finish_register_fn(ccx, sp, sym, node_id, llfn);
1878 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1879 match *sess.entry_fn.borrow() {
1880 Some((entry_id, _)) => node_id == entry_id,
1885 // Create a _rust_main(args: ~[str]) function which will be called from the
1886 // runtime rust_start function
1887 pub fn create_entry_wrapper(ccx: &CrateContext,
1889 main_llfn: ValueRef) {
1890 let et = ccx.sess().entry_type.get().unwrap();
1892 config::EntryMain => {
1893 create_entry_fn(ccx, main_llfn, true);
1895 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
1896 config::EntryNone => {} // Do nothing.
1899 fn create_entry_fn(ccx: &CrateContext,
1900 rust_main: ValueRef,
1901 use_start_lang_item: bool) {
1902 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1905 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
1906 let llbb = "top".with_c_str(|buf| {
1908 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1911 let bld = ccx.builder.b;
1913 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1915 let (start_fn, args) = if use_start_lang_item {
1916 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1918 Err(s) => { ccx.sess().fatal(s.as_slice()); }
1920 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1921 get_item_val(ccx, start_def_id.node)
1923 let start_fn_type = csearch::get_type(ccx.tcx(),
1925 trans_external_path(ccx, start_def_id, start_fn_type)
1929 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1930 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1935 llvm::LLVMGetParam(llfn, 0),
1936 llvm::LLVMGetParam(llfn, 1)
1941 debug!("using user-defined start fn");
1943 llvm::LLVMGetParam(llfn, 0 as c_uint),
1944 llvm::LLVMGetParam(llfn, 1 as c_uint)
1950 let result = llvm::LLVMBuildCall(bld,
1953 args.len() as c_uint,
1956 llvm::LLVMBuildRet(bld, result);
1961 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1962 ty: ty::t, attrs: &[ast::Attribute]) -> String {
1963 match attr::first_attr_value_str_by_name(attrs, "export_name") {
1964 // Use provided name
1965 Some(name) => name.get().to_string(),
1967 _ => ccx.tcx.map.with_path(id, |mut path| {
1968 if attr::contains_name(attrs, "no_mangle") {
1970 path.last().unwrap().to_str()
1972 match weak_lang_items::link_name(attrs) {
1973 Some(name) => name.get().to_string(),
1975 // Usual name mangling
1976 mangle_exported_name(ccx, path, ty, id)
1984 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1985 debug!("get_item_val(id=`{:?}`)", id);
1987 match ccx.item_vals.borrow().find_copy(&id) {
1988 Some(v) => return v,
1992 let mut foreign = false;
1993 let item = ccx.tcx.map.get(id);
1994 let val = match item {
1995 ast_map::NodeItem(i) => {
1996 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1997 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1999 let v = match i.node {
2000 ast::ItemStatic(_, mutbl, ref expr) => {
2001 // If this static came from an external crate, then
2002 // we need to get the symbol from csearch instead of
2003 // using the current crate's name/version
2004 // information in the hash of the symbol
2005 debug!("making {}", sym);
2006 let (sym, is_local) = {
2007 match ccx.external_srcs.borrow().find(&i.id) {
2009 debug!("but found in other crate...");
2010 (csearch::get_symbol(&ccx.sess().cstore,
2017 // We need the translated value here, because for enums the
2018 // LLVM type is not fully determined by the Rust type.
2019 let (v, inlineable) = consts::const_expr(ccx, &**expr, is_local);
2020 ccx.const_values.borrow_mut().insert(id, v);
2021 let mut inlineable = inlineable;
2024 let llty = llvm::LLVMTypeOf(v);
2025 let g = sym.as_slice().with_c_str(|buf| {
2026 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2029 if !ccx.reachable.contains(&id) {
2030 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
2033 // Apply the `unnamed_addr` attribute if
2035 if !ast_util::static_has_significant_address(
2037 i.attrs.as_slice()) {
2038 lib::llvm::SetUnnamedAddr(g, true);
2040 // This is a curious case where we must make
2041 // all of these statics inlineable. If a
2042 // global is not tagged as `#[inline(never)]`,
2043 // then LLVM won't coalesce globals unless they
2044 // have an internal linkage type. This means that
2045 // external crates cannot use this global.
2046 // This is a problem for things like inner
2047 // statics in generic functions, because the
2048 // function will be inlined into another
2049 // crate and then attempt to link to the
2050 // static in the original crate, only to
2051 // find that it's not there. On the other
2052 // side of inlining, the crates knows to
2053 // not declare this static as
2054 // available_externally (because it isn't)
2058 if attr::contains_name(i.attrs.as_slice(),
2060 lib::llvm::set_thread_local(g, true);
2064 debug!("{} not inlined", sym);
2065 ccx.non_inlineable_statics.borrow_mut()
2069 ccx.item_symbols.borrow_mut().insert(i.id, sym);
2074 ast::ItemFn(_, _, abi, _, _) => {
2075 let llfn = if abi == Rust {
2076 register_fn(ccx, i.span, sym, i.id, ty)
2078 foreign::register_rust_fn_with_foreign_abi(ccx,
2083 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2087 _ => fail!("get_item_val: weird result in table")
2090 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2092 Some(sect) => unsafe {
2093 sect.get().with_c_str(|buf| {
2094 llvm::LLVMSetSection(v, buf);
2103 ast_map::NodeTraitMethod(trait_method) => {
2104 debug!("get_item_val(): processing a NodeTraitMethod");
2105 match *trait_method {
2106 ast::Required(_) => {
2107 ccx.sess().bug("unexpected variant: required trait method in \
2110 ast::Provided(m) => {
2111 register_method(ccx, id, &*m)
2116 ast_map::NodeMethod(m) => {
2117 register_method(ccx, id, &*m)
2120 ast_map::NodeForeignItem(ni) => {
2124 ast::ForeignItemFn(..) => {
2125 let abi = ccx.tcx.map.get_foreign_abi(id);
2126 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2127 let name = foreign::link_name(&*ni);
2128 foreign::register_foreign_item_fn(ccx, abi, ty,
2129 name.get().as_slice(),
2132 ast::ForeignItemStatic(..) => {
2133 foreign::register_static(ccx, &*ni)
2138 ast_map::NodeVariant(ref v) => {
2140 let args = match v.node.kind {
2141 ast::TupleVariantKind(ref args) => args,
2142 ast::StructVariantKind(_) => {
2143 fail!("struct variant kind unexpected in get_item_val")
2146 assert!(args.len() != 0u);
2147 let ty = ty::node_id_to_type(ccx.tcx(), id);
2148 let parent = ccx.tcx.map.get_parent(id);
2149 let enm = ccx.tcx.map.expect_item(parent);
2150 let sym = exported_name(ccx,
2153 enm.attrs.as_slice());
2155 llfn = match enm.node {
2156 ast::ItemEnum(_, _) => {
2157 register_fn(ccx, (*v).span, sym, id, ty)
2159 _ => fail!("NodeVariant, shouldn't happen")
2161 set_inline_hint(llfn);
2165 ast_map::NodeStructCtor(struct_def) => {
2166 // Only register the constructor if this is a tuple-like struct.
2167 let ctor_id = match struct_def.ctor_id {
2169 ccx.sess().bug("attempt to register a constructor of \
2170 a non-tuple-like struct")
2172 Some(ctor_id) => ctor_id,
2174 let parent = ccx.tcx.map.get_parent(id);
2175 let struct_item = ccx.tcx.map.expect_item(parent);
2176 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2177 let sym = exported_name(ccx,
2182 let llfn = register_fn(ccx, struct_item.span,
2184 set_inline_hint(llfn);
2189 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2190 variant).as_slice())
2194 // foreign items (extern fns and extern statics) don't have internal
2195 // linkage b/c that doesn't quite make sense. Otherwise items can
2196 // have internal linkage if they're not reachable.
2197 if !foreign && !ccx.reachable.contains(&id) {
2198 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2201 ccx.item_vals.borrow_mut().insert(id, val);
2205 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2206 m: &ast::Method) -> ValueRef {
2207 let mty = ty::node_id_to_type(ccx.tcx(), id);
2209 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2211 let llfn = register_fn(ccx, m.span, sym, id, mty);
2212 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2216 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2218 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2222 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2223 -> encoder::EncodeParams<'r> {
2224 encoder::EncodeParams {
2225 diag: cx.sess().diagnostic(),
2227 reexports2: &cx.exp_map2,
2228 item_symbols: &cx.item_symbols,
2229 non_inlineable_statics: &cx.non_inlineable_statics,
2230 link_meta: &cx.link_meta,
2231 cstore: &cx.sess().cstore,
2232 encode_inlined_item: ie,
2233 reachable: &cx.reachable,
2237 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2240 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2241 *ty != config::CrateTypeExecutable
2247 let encode_inlined_item: encoder::EncodeInlinedItem =
2248 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2250 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2251 let metadata = encoder::encode_metadata(encode_parms, krate);
2252 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2253 .append(match flate::deflate_bytes(metadata.as_slice()) {
2254 Some(compressed) => compressed,
2256 cx.sess().fatal("failed to compress metadata")
2259 let llmeta = C_bytes(cx, compressed.as_slice());
2260 let llconst = C_struct(cx, [llmeta], false);
2261 let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2262 cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2263 let llglobal = name.with_c_str(|buf| {
2265 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2269 llvm::LLVMSetInitializer(llglobal, llconst);
2270 let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2271 name.unwrap_or("rust_metadata").with_c_str(|buf| {
2272 llvm::LLVMSetSection(llglobal, buf)
2278 pub fn trans_crate(krate: ast::Crate,
2279 analysis: CrateAnalysis,
2280 output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2281 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, .. } = analysis;
2283 // Before we touch LLVM, make sure that multithreading is enabled.
2285 use std::sync::{Once, ONCE_INIT};
2286 static mut INIT: Once = ONCE_INIT;
2287 static mut POISONED: bool = false;
2289 if llvm::LLVMStartMultithreaded() != 1 {
2290 // use an extra bool to make sure that all future usage of LLVM
2291 // cannot proceed despite the Once not running more than once.
2297 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2301 let link_meta = link::build_link_meta(&krate,
2302 output.out_filestem.as_slice());
2304 // Append ".rs" to crate name as LLVM module identifier.
2306 // LLVM code generator emits a ".file filename" directive
2307 // for ELF backends. Value of the "filename" is set as the
2308 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2309 // crashes if the module identifier is same as other symbols
2310 // such as a function name in the module.
2311 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2312 let mut llmod_id = link_meta.crateid.name.clone();
2313 llmod_id.push_str(".rs");
2315 let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2316 Sha256::new(), link_meta, reachable);
2318 // First, verify intrinsics.
2319 intrinsic::check_intrinsics(&ccx);
2321 // Next, translate the module.
2323 let _icx = push_ctxt("text");
2324 trans_mod(&ccx, &krate.module);
2327 glue::emit_tydescs(&ccx);
2328 if ccx.sess().opts.debuginfo != NoDebugInfo {
2329 debuginfo::finalize(&ccx);
2332 // Translate the metadata.
2333 let metadata = write_metadata(&ccx, &krate);
2334 if ccx.sess().trans_stats() {
2335 println!("--- trans stats ---");
2336 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2337 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2338 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2339 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2341 println!("n_fns: {}", ccx.stats.n_fns.get());
2342 println!("n_monos: {}", ccx.stats.n_monos.get());
2343 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2344 println!("n_closures: {}", ccx.stats.n_closures.get());
2345 println!("fn stats:");
2346 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2347 insns_b.cmp(&insns_a)
2349 for tuple in ccx.stats.fn_stats.borrow().iter() {
2351 (ref name, ms, insns) => {
2352 println!("{} insns, {} ms, {}", insns, ms, *name);
2357 if ccx.sess().count_llvm_insns() {
2358 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2359 println!("{:7u} {}", *v, *k);
2363 let llcx = ccx.llcx;
2364 let link_meta = ccx.link_meta.clone();
2365 let llmod = ccx.llmod;
2367 let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
2368 ccx.item_symbols.borrow().find(id).map(|s| s.to_string())
2371 // For the purposes of LTO, we add to the reachable set all of the upstream
2372 // reachable extern fns. These functions are all part of the public ABI of
2373 // the final product, so LTO needs to preserve them.
2374 ccx.sess().cstore.iter_crate_data(|cnum, _| {
2375 let syms = csearch::get_reachable_extern_fns(&ccx.sess().cstore, cnum);
2376 reachable.extend(syms.move_iter().map(|did| {
2377 csearch::get_symbol(&ccx.sess().cstore, did)
2381 // Make sure that some other crucial symbols are not eliminated from the
2382 // module. This includes the main function, the crate map (used for debug
2383 // log settings and I/O), and finally the curious rust_stack_exhausted
2384 // symbol. This symbol is required for use by the libmorestack library that
2385 // we link in, so we must ensure that this symbol is not internalized (if
2386 // defined in the crate).
2387 reachable.push("main".to_string());
2388 reachable.push("rust_stack_exhausted".to_string());
2390 // referenced from .eh_frame section on some platforms
2391 reachable.push("rust_eh_personality".to_string());
2392 // referenced from rt/rust_try.ll
2393 reachable.push("rust_eh_personality_catch".to_string());
2395 let metadata_module = ccx.metadata_llmod;
2396 let formats = ccx.tcx.dependency_formats.borrow().clone();
2397 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
2399 (ccx.tcx, CrateTranslation {
2403 metadata_module: metadata_module,
2405 reachable: reachable,
2406 crate_formats: formats,
2407 no_builtins: no_builtins,