1 // Copyright 2012-2013 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 many TypeRefs correspond to one ty::t; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
27 use back::link::{mangle_exported_name};
28 use back::{link, abi};
30 use driver::session::Session;
31 use driver::driver::{CrateAnalysis, CrateTranslation};
32 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
38 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
39 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::base;
43 use middle::trans::build::*;
44 use middle::trans::builder::{Builder, noname};
45 use middle::trans::callee;
46 use middle::trans::common::*;
47 use middle::trans::consts;
48 use middle::trans::controlflow;
49 use middle::trans::datum;
50 use middle::trans::debuginfo;
51 use middle::trans::expr;
52 use middle::trans::foreign;
53 use middle::trans::glue;
54 use middle::trans::inline;
55 use middle::trans::machine;
56 use middle::trans::machine::{llalign_of_min, llsize_of};
57 use middle::trans::meth;
58 use middle::trans::monomorphize;
59 use middle::trans::tvec;
60 use middle::trans::type_of;
61 use middle::trans::type_of::*;
63 use util::common::indenter;
64 use util::ppaux::{Repr, ty_to_str};
66 use middle::trans::type_::Type;
68 use std::c_str::ToCStr;
70 use std::hashmap::HashMap;
72 use std::libc::c_uint;
78 use syntax::ast::ident;
79 use syntax::ast_map::{path, path_elt_to_str, path_name};
80 use syntax::ast_util::{local_def};
82 use syntax::attr::AttrMetaMethods;
83 use syntax::codemap::span;
84 use syntax::parse::token;
85 use syntax::parse::token::{special_idents};
86 use syntax::print::pprust::stmt_to_str;
88 use syntax::{ast, ast_util, codemap, ast_map};
89 use syntax::abi::{X86, X86_64, Arm, Mips};
91 pub use middle::trans::context::task_llcx;
93 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
95 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
96 let opt = local_data::get(task_local_insn_key, |k| k.map(|&k| *k));
102 pub fn init_insn_ctxt() {
103 local_data::set(task_local_insn_key, @~[]);
106 pub struct _InsnCtxt { _x: () }
109 impl Drop for _InsnCtxt {
111 do local_data::modify(task_local_insn_key) |c| {
112 do c.map_consume |ctx| {
113 let mut ctx = (*ctx).clone();
121 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
122 debug!("new InsnCtxt: %s", s);
123 do local_data::modify(task_local_insn_key) |c| {
124 do c.map_consume |ctx| {
125 let mut ctx = (*ctx).clone();
133 fn fcx_has_nonzero_span(fcx: &FunctionContext) -> bool {
136 Some(span) => *span.lo != 0 || *span.hi != 0
140 struct StatRecorder<'self> {
141 ccx: @mut CrateContext,
147 impl<'self> StatRecorder<'self> {
148 pub fn new(ccx: @mut CrateContext,
149 name: &'self str) -> StatRecorder<'self> {
150 let start = if ccx.sess.trans_stats() {
151 time::precise_time_ns()
155 let istart = ccx.stats.n_llvm_insns;
166 impl<'self> Drop for StatRecorder<'self> {
168 if self.ccx.sess.trans_stats() {
169 let end = time::precise_time_ns();
170 let elapsed = ((end - self.start) / 1_000_000) as uint;
171 let iend = self.ccx.stats.n_llvm_insns;
172 self.ccx.stats.fn_stats.push((self.name.to_owned(),
174 iend - self.istart));
175 self.ccx.stats.n_fns += 1;
176 // Reset LLVM insn count to avoid compound costs.
177 self.ccx.stats.n_llvm_insns = self.istart;
182 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
183 let llfn: ValueRef = do name.to_c_str().with_ref |buf| {
185 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
189 lib::llvm::SetFunctionCallConv(llfn, cc);
193 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
194 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
197 // Only use this if you are going to actually define the function. It's
198 // not valid to simply declare a function as internal.
199 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
200 let llfn = decl_cdecl_fn(llmod, name, ty);
201 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
205 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
206 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
207 match externs.find_copy(&name) {
211 let f = decl_fn(llmod, name, cc, ty);
212 externs.insert(name, f);
216 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
217 name: @str, ty: Type) -> ValueRef {
218 match externs.find_copy(&name) {
223 let c = do name.to_c_str().with_ref |buf| {
224 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
226 externs.insert(name, c);
230 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
231 let _icx = push_ctxt("umax");
232 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
233 return Select(cx, cond, b, a);
236 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
237 let _icx = push_ctxt("umin");
238 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
239 return Select(cx, cond, a, b);
242 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
243 // The type of the returned pointer is always i8*. If you care about the
244 // return type, use bump_ptr().
245 pub fn ptr_offs(bcx: @mut Block, base: ValueRef, sz: ValueRef) -> ValueRef {
246 let _icx = push_ctxt("ptr_offs");
247 let raw = PointerCast(bcx, base, Type::i8p());
248 InBoundsGEP(bcx, raw, [sz])
251 // Increment a pointer by a given amount and then cast it to be a pointer
253 pub fn bump_ptr(bcx: @mut Block, t: ty::t, base: ValueRef, sz: ValueRef) ->
255 let _icx = push_ctxt("bump_ptr");
257 let bumped = ptr_offs(bcx, base, sz);
258 let typ = type_of(ccx, t).ptr_to();
259 PointerCast(bcx, bumped, typ)
262 // Returns a pointer to the body for the box. The box may be an opaque
263 // box. The result will be casted to the type of body_t, if it is statically
266 // The runtime equivalent is box_body() in "rust_internal.h".
267 pub fn opaque_box_body(bcx: @mut Block,
269 boxptr: ValueRef) -> ValueRef {
270 let _icx = push_ctxt("opaque_box_body");
272 let ty = type_of(ccx, body_t);
273 let ty = Type::box(ccx, &ty);
274 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
275 GEPi(bcx, boxptr, [0u, abi::box_field_body])
278 // malloc_raw_dyn: allocates a box to contain a given type, but with a
279 // potentially dynamic size.
280 pub fn malloc_raw_dyn(bcx: @mut Block,
283 size: ValueRef) -> Result {
284 let _icx = push_ctxt("malloc_raw");
287 fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::def_id {
288 let li = &bcx.tcx().lang_items;
289 match li.require(it) {
292 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
293 bcx.ty_to_str(t), s));
298 if heap == heap_exchange {
299 let llty_value = type_of::type_of(ccx, t);
303 let r = callee::trans_lang_call(
305 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
308 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
310 // we treat ~fn, @fn and @[] as @ here, which isn't ideal
311 let (mk_fn, langcall) = match heap {
312 heap_managed | heap_managed_unique => {
314 require_alloc_fn(bcx, t, MallocFnLangItem))
316 heap_exchange_closure => {
318 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
320 _ => fail!("heap_exchange already handled")
323 // Grab the TypeRef type of box_ptr_ty.
324 let box_ptr_ty = mk_fn(bcx.tcx(), t);
325 let llty = type_of(ccx, box_ptr_ty);
327 // Get the tydesc for the body:
328 let static_ti = get_tydesc(ccx, t);
329 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
332 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
333 let r = callee::trans_lang_call(
338 let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
339 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
344 // malloc_raw: expects an unboxed type and returns a pointer to
345 // enough space for a box of that type. This includes a rust_opaque_box
347 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
348 let ty = type_of(bcx.ccx(), t);
349 let size = llsize_of(bcx.ccx(), ty);
350 malloc_raw_dyn(bcx, t, heap, size)
353 pub struct MallocResult {
359 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
360 // and pulls out the body
361 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
363 assert!(heap != heap_exchange);
364 let _icx = push_ctxt("malloc_general");
365 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
366 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
368 MallocResult { bcx: bcx, box: llbox, body: body }
371 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
372 let ty = type_of(bcx.ccx(), t);
373 assert!(heap != heap_exchange);
374 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
376 pub fn malloc_boxed(bcx: @mut Block, t: ty::t)
378 malloc_general(bcx, t, heap_managed)
381 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
382 if ty::type_contents(bcx.tcx(), t).contains_managed() {
389 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
390 assert!(heap != heap_exchange);
391 if heap == heap_managed_unique {
392 // In cases where we are looking at a unique-typed allocation in the
393 // managed heap (thus have refcount 1 from the managed allocator),
394 // such as a ~(@foo) or such. These need to have their refcount forced
395 // to -2 so the annihilator ignores them.
396 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
397 let rc_val = C_int(bcx.ccx(), -2);
398 Store(bcx, rc_val, rc);
402 // Type descriptor and type glue stuff
404 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
405 get_tydesc(ccx, t).tydesc
408 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
409 match ccx.tydescs.find(&t) {
416 ccx.stats.n_static_tydescs += 1u;
417 let inf = glue::declare_tydesc(ccx, t);
418 ccx.tydescs.insert(t, inf);
422 pub fn set_optimize_for_size(f: ValueRef) {
423 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
426 pub fn set_no_inline(f: ValueRef) {
427 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
430 pub fn set_no_unwind(f: ValueRef) {
431 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
434 // Tell LLVM to emit the information necessary to unwind the stack for the
436 pub fn set_uwtable(f: ValueRef) {
437 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
440 pub fn set_inline_hint(f: ValueRef) {
441 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
444 pub fn set_inline_hint_if_appr(attrs: &[ast::Attribute],
447 match find_inline_attr(attrs) {
448 InlineHint => set_inline_hint(llfn),
449 InlineAlways => set_always_inline(llfn),
450 InlineNever => set_no_inline(llfn),
451 InlineNone => { /* fallthrough */ }
455 pub fn set_always_inline(f: ValueRef) {
456 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
459 pub fn set_fixed_stack_segment(f: ValueRef) {
460 lib::llvm::SetFixedStackSegmentAttribute(f);
463 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
464 if ty::type_is_structural(t) {
465 set_optimize_for_size(f);
466 } else { set_always_inline(f); }
469 // Double-check that we never ask LLVM to declare the same symbol twice. It
470 // silently mangles such symbols, breaking our linkage model.
471 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
472 if ccx.all_llvm_symbols.contains(&sym) {
473 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
475 ccx.all_llvm_symbols.insert(sym);
479 pub fn get_res_dtor(ccx: @mut CrateContext,
481 parent_id: ast::def_id,
484 let _icx = push_ctxt("trans_res_dtor");
485 if !substs.is_empty() {
486 let did = if did.crate != ast::LOCAL_CRATE {
487 inline::maybe_instantiate_inline(ccx, did)
491 assert_eq!(did.crate, ast::LOCAL_CRATE);
492 let tsubsts = ty::substs {regions: ty::ErasedRegions,
494 tps: /*bad*/ substs.to_owned() };
495 let (val, _) = monomorphize::monomorphic_fn(ccx,
503 } else if did.crate == ast::LOCAL_CRATE {
504 get_item_val(ccx, did.node)
507 let name = csearch::get_symbol(ccx.sess.cstore, did);
508 let class_ty = ty::subst_tps(tcx,
511 ty::lookup_item_type(tcx, parent_id).ty);
512 let llty = type_of_dtor(ccx, class_ty);
513 let name = name.to_managed(); // :-(
514 get_extern_fn(&mut ccx.externs,
517 lib::llvm::CCallConv,
522 // Structural comparison: a rather involved form of glue.
523 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
524 if cx.sess.opts.save_temps {
525 do s.to_c_str().with_ref |buf| {
527 llvm::LLVMSetValueName(v, buf)
534 // Used only for creating scalar comparison glue.
535 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
537 // NB: This produces an i1, not a Rust bool (i8).
538 pub fn compare_scalar_types(cx: @mut Block,
544 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
546 match ty::get(t).sty {
547 ty::ty_nil => rslt(cx, f(nil_type)),
548 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
549 ty::ty_int(_) => rslt(cx, f(signed_int)),
550 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
551 ty::ty_float(_) => rslt(cx, f(floating_point)),
554 controlflow::trans_fail(
556 @"attempt to compare values of type type"),
560 // Should never get here, because t is scalar.
561 cx.sess().bug("non-scalar type passed to \
562 compare_scalar_types")
568 // A helper function to do the actual comparison of scalar values.
569 pub fn compare_scalar_values(cx: @mut Block,
575 let _icx = push_ctxt("compare_scalar_values");
576 fn die(cx: @mut Block) -> ! {
577 cx.tcx().sess.bug("compare_scalar_values: must be a\
578 comparison operator");
582 // We don't need to do actual comparisons for nil.
583 // () == () holds but () < () does not.
585 ast::eq | ast::le | ast::ge => return C_i1(true),
586 ast::ne | ast::lt | ast::gt => return C_i1(false),
587 // refinements would be nice
593 ast::eq => lib::llvm::RealOEQ,
594 ast::ne => lib::llvm::RealUNE,
595 ast::lt => lib::llvm::RealOLT,
596 ast::le => lib::llvm::RealOLE,
597 ast::gt => lib::llvm::RealOGT,
598 ast::ge => lib::llvm::RealOGE,
601 return FCmp(cx, cmp, lhs, rhs);
605 ast::eq => lib::llvm::IntEQ,
606 ast::ne => lib::llvm::IntNE,
607 ast::lt => lib::llvm::IntSLT,
608 ast::le => lib::llvm::IntSLE,
609 ast::gt => lib::llvm::IntSGT,
610 ast::ge => lib::llvm::IntSGE,
613 return ICmp(cx, cmp, lhs, rhs);
617 ast::eq => lib::llvm::IntEQ,
618 ast::ne => lib::llvm::IntNE,
619 ast::lt => lib::llvm::IntULT,
620 ast::le => lib::llvm::IntULE,
621 ast::gt => lib::llvm::IntUGT,
622 ast::ge => lib::llvm::IntUGE,
625 return ICmp(cx, cmp, lhs, rhs);
630 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
632 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
633 return Load(cx, GEPi(cx, p, idxs));
636 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
637 Store(cx, v, GEPi(cx, p, idxs));
640 // Iterates through the elements of a structural type.
641 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
642 f: val_and_ty_fn) -> @mut Block {
643 let _icx = push_ctxt("iter_structural_ty");
645 fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
646 variant: @ty::VariantInfo,
647 tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
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 ty::subst_tps(tcx, tps, None, arg));
661 match ty::get(t).sty {
662 ty::ty_struct(*) => {
663 let repr = adt::represent_type(cx.ccx(), t);
664 do 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_estr(ty::vstore_fixed(_)) |
672 ty::ty_evec(_, ty::vstore_fixed(_)) => {
673 let (base, len) = tvec::get_base_and_len(cx, av, t);
674 cx = tvec::iter_vec_raw(cx, base, t, 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) => {
686 let repr = adt::represent_type(ccx, t);
687 let variants = ty::enum_variants(ccx.tcx, tid);
688 let n_variants = (*variants).len();
690 // NB: we must hit the discriminant first so that structural
691 // comparison know not to proceed when the discriminants differ.
693 match adt::trans_switch(cx, repr, av) {
694 (_match::single, None) => {
695 cx = iter_variant(cx, repr, av, variants[0],
698 (_match::switch, Some(lldiscrim_a)) => {
699 cx = f(cx, lldiscrim_a, ty::mk_int());
700 let unr_cx = sub_block(cx, "enum-iter-unr");
702 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
704 let next_cx = sub_block(cx, "enum-iter-next");
706 for variant in (*variants).iter() {
708 sub_block(cx, ~"enum-iter-variant-" +
709 uint::to_str(variant.disr_val));
711 iter_variant(variant_cx, repr, av, *variant,
712 substs.tps, |x,y,z| f(x,y,z));
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")
720 Br(variant_cx, next_cx.llbb);
724 _ => ccx.sess.unimpl("value from adt::trans_switch \
725 in iter_structural_ty")
728 _ => cx.sess().unimpl("type in iter_structural_ty")
733 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::binop,
734 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
735 cast_shift_rhs(op, lhs, rhs,
736 |a,b| Trunc(cx, a, b),
737 |a,b| ZExt(cx, a, b))
740 pub fn cast_shift_const_rhs(op: ast::binop,
741 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
742 cast_shift_rhs(op, lhs, rhs,
743 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
744 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
747 pub fn cast_shift_rhs(op: ast::binop,
748 lhs: ValueRef, rhs: ValueRef,
749 trunc: &fn(ValueRef, Type) -> ValueRef,
750 zext: &fn(ValueRef, Type) -> ValueRef)
752 // Shifts may have any size int on the rhs
754 if ast_util::is_shift_binop(op) {
755 let rhs_llty = val_ty(rhs);
756 let lhs_llty = val_ty(lhs);
757 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
758 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
761 } else if lhs_sz > rhs_sz {
762 // FIXME (#1877: If shifting by negative
763 // values becomes not undefined then this is wrong.
774 pub fn fail_if_zero(cx: @mut Block, span: span, divrem: ast::binop,
775 rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
776 let text = if divrem == ast::div {
777 @"attempted to divide by zero"
779 @"attempted remainder with a divisor of zero"
781 let is_zero = match ty::get(rhs_t).sty {
783 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
784 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
787 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
788 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
791 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
792 ty_to_str(cx.ccx().tcx, rhs_t));
795 do with_cond(cx, is_zero) |bcx| {
796 controlflow::trans_fail(bcx, Some(span), text)
800 pub fn null_env_ptr(bcx: @mut Block) -> ValueRef {
801 C_null(Type::opaque_box(bcx.ccx()).ptr_to())
804 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
806 let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
807 match ty::get(t).sty {
808 ty::ty_bare_fn(_) | ty::ty_closure(_) => {
809 let llty = type_of_fn_from_ty(ccx, t);
810 return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
811 lib::llvm::CCallConv, llty);
814 let llty = type_of(ccx, t);
815 return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
820 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef])
821 -> (ValueRef, @mut Block) {
822 let _icx = push_ctxt("invoke_");
824 return (C_null(Type::i8()), bcx);
827 match bcx.node_info {
828 None => debug!("invoke at ???"),
830 debug!("invoke at %s",
831 bcx.sess().codemap.span_to_str(node_info.span));
835 if need_invoke(bcx) {
837 debug!("invoking %x at %x",
838 ::std::cast::transmute(llfn),
839 ::std::cast::transmute(bcx.llbb));
840 for &llarg in llargs.iter() {
841 debug!("arg: %x", ::std::cast::transmute(llarg));
844 let normal_bcx = sub_block(bcx, "normal return");
845 let llresult = Invoke(bcx,
849 get_landing_pad(bcx));
850 return (llresult, normal_bcx);
853 debug!("calling %x at %x",
854 ::std::cast::transmute(llfn),
855 ::std::cast::transmute(bcx.llbb));
856 for &llarg in llargs.iter() {
857 debug!("arg: %x", ::std::cast::transmute(llarg));
860 let llresult = Call(bcx, llfn, llargs);
861 return (llresult, bcx);
865 pub fn need_invoke(bcx: @mut Block) -> bool {
866 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
870 // Avoid using invoke if we are already inside a landing pad.
875 if have_cached_lpad(bcx) {
879 // Walk the scopes to look for cleanups
881 let mut cur_scope = cur.scope;
883 cur_scope = match cur_scope {
885 for cleanup in inf.cleanups.iter() {
887 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
888 if cleanup_type == normal_exit_and_unwind {
897 cur = match cur.parent {
907 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
909 do in_lpad_scope_cx(bcx) |inf| {
910 match inf.landing_pad {
911 Some(_) => res = true,
918 pub fn in_lpad_scope_cx(bcx: @mut Block, f: &fn(si: &mut ScopeInfo)) {
920 let mut cur_scope = bcx.scope;
922 cur_scope = match cur_scope {
924 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
931 bcx = block_parent(bcx);
938 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
939 let _icx = push_ctxt("get_landing_pad");
941 let mut cached = None;
942 let mut pad_bcx = bcx; // Guaranteed to be set below
943 do in_lpad_scope_cx(bcx) |inf| {
944 // If there is a valid landing pad still around, use it
945 match inf.landing_pad {
946 Some(target) => cached = Some(target),
948 pad_bcx = lpad_block(bcx, "unwind");
949 inf.landing_pad = Some(pad_bcx.llbb);
953 // Can't return from block above
954 match cached { Some(b) => return b, None => () }
955 // The landing pad return type (the type being propagated). Not sure what
956 // this represents but it's determined by the personality function and
957 // this is what the EH proposal example uses.
958 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
959 // The exception handling personality function. This is the C++
960 // personality function __gxx_personality_v0, wrapped in our naming
962 let personality = bcx.ccx().upcalls.rust_personality;
963 // The only landing pad clause will be 'cleanup'
964 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
965 // The landing pad block is a cleanup
966 SetCleanup(pad_bcx, llretval);
968 // Because we may have unwound across a stack boundary, we must call into
969 // the runtime to figure out which stack segment we are on and place the
970 // stack limit back into the TLS.
971 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
973 // We store the retval in a function-central alloca, so that calls to
974 // Resume can find it.
975 match bcx.fcx.personality {
976 Some(addr) => Store(pad_bcx, llretval, addr),
978 let addr = alloca(pad_bcx, val_ty(llretval), "");
979 bcx.fcx.personality = Some(addr);
980 Store(pad_bcx, llretval, addr);
984 // Unwind all parent scopes, and finish with a Resume instr
985 cleanup_and_leave(pad_bcx, None, None);
989 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::NodeId) -> @mut Block {
990 let mut bcx_sid = bcx;
991 let mut cur_scope = bcx_sid.scope;
993 cur_scope = match cur_scope {
995 match inf.node_info {
996 Some(NodeInfo { id, _ }) if id == scope_id => {
999 // FIXME(#6268, #6248) hacky cleanup for nested method calls
1000 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1007 bcx_sid = match bcx_sid.parent {
1008 None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1009 Some(bcx_par) => bcx_par
1018 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1019 if ty::type_is_bot(t) {
1020 return C_null(Type::i8p());
1022 let llptr = alloc_ty(bcx, t, "");
1023 Store(bcx, v, llptr);
1027 // Since this function does *not* root, it is the caller's responsibility to
1028 // ensure that the referent is pointed to by a root.
1029 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1030 let llptr = alloca(cx, val_ty(v), "");
1031 Store(cx, v, llptr);
1035 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1036 let _icx = push_ctxt("spill_if_immediate");
1037 if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1041 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1042 let _icx = push_ctxt("load_if_immediate");
1043 if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1047 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<span>, trace_str: @str) {
1048 if !bcx.sess().trace() { return; }
1049 let _icx = push_ctxt("trans_trace");
1050 add_comment(bcx, trace_str);
1051 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1052 let (V_filename, V_line) = match sp_opt {
1054 let sess = bcx.sess();
1055 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1056 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1059 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1062 let ccx = bcx.ccx();
1063 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1064 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1065 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1066 Call(bcx, ccx.upcalls.trace, args);
1069 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1070 match local.pat.node {
1071 ast::pat_wild => true, _ => false
1075 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1077 debug!("init_local(bcx=%s, local.id=%?)",
1078 bcx.to_str(), local.id);
1079 let _indenter = indenter();
1081 let _icx = push_ctxt("init_local");
1083 if ignore_lhs(bcx, local) {
1084 // Handle let _ = e; just like e;
1087 return expr::trans_into(bcx, init, expr::Ignore);
1089 None => { return bcx; }
1093 _match::store_local(bcx, local.pat, local.init)
1096 pub fn trans_stmt(cx: @mut Block, s: &ast::stmt) -> @mut Block {
1097 let _icx = push_ctxt("trans_stmt");
1098 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1100 if cx.sess().asm_comments() {
1101 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1105 debuginfo::update_source_pos(cx, s.span);
1108 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1109 bcx = expr::trans_into(cx, e, expr::Ignore);
1111 ast::stmt_decl(d, _) => {
1113 ast::decl_local(ref local) => {
1114 bcx = init_local(bcx, *local);
1115 if cx.sess().opts.extra_debuginfo
1116 && fcx_has_nonzero_span(bcx.fcx) {
1117 debuginfo::create_local_var_metadata(bcx, *local);
1120 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1123 ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1129 // You probably don't want to use this one. See the
1130 // next three functions instead.
1131 pub fn new_block(cx: @mut FunctionContext,
1132 parent: Option<@mut Block>,
1133 scope: Option<@mut ScopeInfo>,
1136 opt_node_info: Option<NodeInfo>)
1139 let llbb = do name.to_c_str().with_ref |buf| {
1140 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1142 let bcx = @mut Block::new(llbb,
1148 for cx in parent.iter() {
1158 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1159 node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1167 node_info: node_info,
1171 // Use this when you're at the top block of a function or the like.
1172 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1174 return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1175 "function top level", opt_node_info);
1178 pub fn scope_block(bcx: @mut Block,
1179 opt_node_info: Option<NodeInfo>,
1180 n: &str) -> @mut Block {
1181 return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1185 pub fn loop_scope_block(bcx: @mut Block,
1186 loop_break: @mut Block,
1187 loop_label: Option<ident>,
1189 opt_node_info: Option<NodeInfo>) -> @mut Block {
1190 return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1192 loop_break: Some(loop_break),
1193 loop_label: loop_label,
1197 node_info: opt_node_info,
1198 }), bcx.is_lpad, n, opt_node_info);
1201 // Use this when creating a block for the inside of a landing pad.
1202 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1203 new_block(bcx.fcx, Some(bcx), None, true, n, None)
1206 // Use this when you're making a general CFG BB within a scope.
1207 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1208 new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1211 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1212 @mut Block::new(llbb, None, is_lpad, None, fcx)
1216 // trans_block_cleanups: Go through all the cleanups attached to this
1217 // block and execute them.
1219 // When translating a block that introduces new variables during its scope, we
1220 // need to make sure those variables go out of scope when the block ends. We
1221 // do that by running a 'cleanup' function for each variable.
1222 // trans_block_cleanups runs all the cleanup functions for the block.
1223 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1224 trans_block_cleanups_(bcx, cleanups, false)
1227 pub fn trans_block_cleanups_(bcx: @mut Block,
1228 cleanups: &[cleanup],
1229 /* cleanup_cx: block, */
1230 is_lpad: bool) -> @mut Block {
1231 let _icx = push_ctxt("trans_block_cleanups");
1232 // NB: Don't short-circuit even if this block is unreachable because
1233 // GC-based cleanup needs to the see that the roots are live.
1235 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1236 if bcx.unreachable && !no_lpads { return bcx; }
1238 for cu in cleanups.rev_iter() {
1240 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1241 // Some types don't need to be cleaned up during
1242 // landing pads because they can be freed en mass later
1243 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1252 // In the last argument, Some(block) mean jump to this block, and none means
1253 // this is a landing pad and leaving should be accomplished with a resume
1255 pub fn cleanup_and_leave(bcx: @mut Block,
1256 upto: Option<BasicBlockRef>,
1257 leave: Option<BasicBlockRef>) {
1258 let _icx = push_ctxt("cleanup_and_leave");
1261 let is_lpad = leave == None;
1263 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1265 if bcx.sess().trace() {
1268 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1271 let mut cur_scope = cur.scope;
1273 cur_scope = match cur_scope {
1274 Some (inf) if !inf.empty_cleanups() => {
1275 let (sub_cx, dest, inf_cleanups) = {
1276 let inf = &mut *inf;
1278 let mut dest = None;
1280 let r = (*inf).cleanup_paths.rev_iter().find_(|cp| cp.target == leave);
1281 for cp in r.iter() {
1282 if cp.size == inf.cleanups.len() {
1288 dest = Some(cp.dest);
1291 let sub_cx = sub_block(bcx, "cleanup");
1292 Br(bcx, sub_cx.llbb);
1293 inf.cleanup_paths.push(cleanup_path {
1295 size: inf.cleanups.len(),
1298 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1300 bcx = trans_block_cleanups_(sub_cx,
1303 for &dest in dest.iter() {
1309 Some(inf) => inf.parent,
1315 Some(bb) => { if cur.llbb == bb { break; } }
1318 cur = match cur.parent {
1320 None => { assert!(upto.is_none()); break; }
1324 Some(target) => Br(bcx, target),
1325 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.get())); }
1329 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1330 let _icx = push_ctxt("cleanup_block");
1334 debug!("cleanup_block: %s", cur.to_str());
1336 if bcx.sess().trace() {
1339 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1342 let mut cur_scope = cur.scope;
1344 cur_scope = match cur_scope {
1346 bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1354 Some(bb) => { if cur.llbb == bb { break; } }
1357 cur = match cur.parent {
1359 None => { assert!(upto.is_none()); break; }
1365 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1366 let _icx = push_ctxt("cleanup_and_Br");
1367 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1370 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1371 let _icx = push_ctxt("leave_block");
1372 let next_cx = sub_block(block_parent(out_of), "next");
1373 if bcx.unreachable { Unreachable(next_cx); }
1374 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1378 pub fn with_scope(bcx: @mut Block,
1379 opt_node_info: Option<NodeInfo>,
1381 f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1382 let _icx = push_ctxt("with_scope");
1384 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1385 bcx.to_str(), opt_node_info, name);
1386 let _indenter = indenter();
1388 let scope = simple_block_scope(bcx.scope, opt_node_info);
1389 bcx.scope = Some(scope);
1391 let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1392 bcx.scope = scope.parent;
1396 pub fn with_scope_result(bcx: @mut Block,
1397 opt_node_info: Option<NodeInfo>,
1399 f: &fn(@mut Block) -> Result) -> Result {
1400 let _icx = push_ctxt("with_scope_result");
1402 let scope = simple_block_scope(bcx.scope, opt_node_info);
1403 bcx.scope = Some(scope);
1404 let Result { bcx: out_bcx, val } = f(bcx);
1405 let out_bcx = trans_block_cleanups_(out_bcx,
1406 (scope.cleanups).clone(),
1408 bcx.scope = scope.parent;
1413 pub fn with_scope_datumblock(bcx: @mut Block, opt_node_info: Option<NodeInfo>,
1414 name: &str, f: &fn(@mut Block) -> datum::DatumBlock)
1415 -> datum::DatumBlock {
1416 use middle::trans::datum::DatumBlock;
1418 let _icx = push_ctxt("with_scope_result");
1419 let scope_cx = scope_block(bcx, opt_node_info, name);
1420 Br(bcx, scope_cx.llbb);
1421 let DatumBlock {bcx, datum} = f(scope_cx);
1422 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1425 pub fn block_locals(b: &ast::Block, it: &fn(@ast::Local)) {
1426 for s in b.stmts.iter() {
1428 ast::stmt_decl(d, _) => {
1430 ast::decl_local(ref local) => it(*local),
1431 _ => {} /* fall through */
1434 _ => {} /* fall through */
1439 pub fn with_cond(bcx: @mut Block, val: ValueRef, f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1440 let _icx = push_ctxt("with_cond");
1441 let next_cx = base::sub_block(bcx, "next");
1442 let cond_cx = base::sub_block(bcx, "cond");
1443 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1444 let after_cx = f(cond_cx);
1445 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1449 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1450 let _icx = push_ctxt("call_memcpy");
1452 let key = match ccx.sess.targ_cfg.arch {
1453 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1454 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1456 let memcpy = ccx.intrinsics.get_copy(&key);
1457 let src_ptr = PointerCast(cx, src, Type::i8p());
1458 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1459 let size = IntCast(cx, n_bytes, ccx.int_type);
1460 let align = C_i32(align as i32);
1461 let volatile = C_i1(false);
1462 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1465 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1466 let _icx = push_ctxt("memcpy_ty");
1467 let ccx = bcx.ccx();
1468 if ty::type_is_structural(t) {
1469 let llty = type_of::type_of(ccx, t);
1470 let llsz = llsize_of(ccx, llty);
1471 let llalign = llalign_of_min(ccx, llty);
1472 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1474 Store(bcx, Load(bcx, src), dst);
1478 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1479 if cx.unreachable { return; }
1480 let _icx = push_ctxt("zero_mem");
1483 let llty = type_of::type_of(ccx, t);
1484 memzero(&B(bcx), llptr, llty);
1487 // Always use this function instead of storing a zero constant to the memory
1488 // in question. If you store a zero constant, LLVM will drown in vreg
1489 // allocation for large data structures, and the generated code will be
1490 // awful. (A telltale sign of this is large quantities of
1491 // `mov [byte ptr foo],0` in the generated code.)
1492 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1493 let _icx = push_ctxt("memzero");
1496 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1497 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1498 X86_64 => "llvm.memset.p0i8.i64"
1501 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1502 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1503 let llzeroval = C_u8(0);
1504 let size = machine::llsize_of(ccx, ty);
1505 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1506 let volatile = C_i1(false);
1507 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1510 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1511 let _icx = push_ctxt("alloc_ty");
1512 let ccx = bcx.ccx();
1513 let ty = type_of::type_of(ccx, t);
1514 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1515 let val = alloca(bcx, ty, name);
1519 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1520 alloca_maybe_zeroed(cx, ty, name, false)
1523 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1524 let _icx = push_ctxt("alloca");
1527 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1530 let p = Alloca(cx, ty, name);
1532 let b = cx.fcx.ccx.builder();
1533 b.position_before(cx.fcx.alloca_insert_pt.get());
1539 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1540 let _icx = push_ctxt("arrayalloca");
1543 return llvm::LLVMGetUndef(ty.to_ref());
1546 return ArrayAlloca(cx, ty, v);
1549 pub struct BasicBlocks {
1553 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1555 let cx = task_llcx();
1556 do "static_allocas".to_c_str().with_ref | buf| {
1557 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1562 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1564 let cx = task_llcx();
1565 do "return".to_c_str().with_ref |buf| {
1566 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1571 // Creates and returns space for, or returns the argument representing, the
1572 // slot where the return value of the function must go.
1573 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1575 if !ty::type_is_immediate(fcx.ccx.tcx, output_type) {
1576 llvm::LLVMGetParam(fcx.llfn, 0)
1578 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1579 let bcx = fcx.entry_bcx.get();
1580 Alloca(bcx, lloutputtype, "__make_return_pointer")
1585 // NB: must keep 4 fns in sync:
1588 // - create_llargs_for_fn_args.
1591 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1597 param_substs: Option<@param_substs>,
1598 opt_node_info: Option<NodeInfo>,
1600 -> @mut FunctionContext {
1601 for p in param_substs.iter() { p.validate(); }
1603 debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1605 path_str(ccx.sess, path),
1607 param_substs.repr(ccx.tcx));
1609 let substd_output_type = match param_substs {
1610 None => output_type,
1612 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1615 let is_immediate = ty::type_is_immediate(ccx.tcx, substd_output_type);
1616 let fcx = @mut FunctionContext {
1619 llvm::LLVMGetUndef(Type::i8p().to_ref())
1623 alloca_insert_pt: None,
1628 has_immediate_return_value: is_immediate,
1629 llargs: @mut HashMap::new(),
1630 lllocals: @mut HashMap::new(),
1631 llupvars: @mut HashMap::new(),
1633 param_substs: param_substs,
1638 fcx.llenv = unsafe {
1639 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1643 let entry_bcx = top_scope_block(fcx, opt_node_info);
1644 Load(entry_bcx, C_null(Type::i8p()));
1646 fcx.entry_bcx = Some(entry_bcx);
1647 fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1650 if !ty::type_is_nil(substd_output_type) && !(is_immediate && skip_retptr) {
1651 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1656 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1661 -> @mut FunctionContext {
1662 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1665 // NB: must keep 4 fns in sync:
1668 // - create_llargs_for_fn_args.
1672 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1673 // allocas created for them.
1675 // When we translate a function, we need to map its incoming arguments to the
1676 // spaces that have been created for them (by code in the llallocas field of
1677 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1678 // field of the fn_ctxt with
1679 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1683 let _icx = push_ctxt("create_llargs_for_fn_args");
1686 impl_self(tt, self_mode) => {
1687 cx.llself = Some(ValSelfData {
1690 is_copy: self_mode == ty::ByCopy
1696 // Return an array containing the ValueRefs that we get from
1697 // llvm::LLVMGetParam for each argument.
1698 vec::from_fn(args.len(), |i| {
1700 let arg_n = cx.arg_pos(i);
1702 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1704 // FIXME #7260: aliasing should be determined by monomorphized ty::t
1706 // `~` pointers never alias other parameters, because ownership was transferred
1707 ast::ty_uniq(_) => {
1708 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1710 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1711 // those in the other parameters and then mark it as `noalias` if there aren't any
1720 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1723 raw_llargs: &[ValueRef],
1724 arg_tys: &[ty::t]) -> @mut Block {
1725 let _icx = push_ctxt("copy_args_to_allocas");
1730 let self_val = if slf.is_copy
1731 && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1732 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1733 let alloc = alloc_ty(bcx, slf.t, "__self");
1734 Store(bcx, tmp, alloc);
1737 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1740 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1741 add_clean(bcx, self_val, slf.t);
1746 for arg_n in range(0u, arg_tys.len()) {
1747 let arg_ty = arg_tys[arg_n];
1748 let raw_llarg = raw_llargs[arg_n];
1750 // For certain mode/type combinations, the raw llarg values are passed
1751 // by value. However, within the fn body itself, we want to always
1752 // have all locals and arguments be by-ref so that we can cancel the
1753 // cleanup and for better interaction with LLVM's debug info. So, if
1754 // the argument would be passed by value, we store it into an alloca.
1755 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1756 // the event it's not truly needed.
1757 // only by value if immediate:
1758 let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1759 let alloc = alloc_ty(bcx, arg_ty, "__arg");
1760 Store(bcx, raw_llarg, alloc);
1765 bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1767 if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1768 debuginfo::create_argument_metadata(bcx, &args[arg_n]);
1775 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1776 // and builds the return block.
1777 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1778 let _icx = push_ctxt("finish_fn");
1780 let ret_cx = match fcx.llreturn {
1782 if !last_bcx.terminated {
1783 Br(last_bcx, llreturn);
1785 raw_block(fcx, false, llreturn)
1789 build_return_block(fcx, ret_cx);
1793 // Builds the return block for a function.
1794 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1795 // Return the value if this function immediate; otherwise, return void.
1796 if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
1797 Ret(ret_cx, Load(ret_cx, fcx.llretptr.get()))
1803 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1805 // trans_closure: Builds an LLVM function out of a source function.
1806 // If the function closes over its environment a closure will be
1808 pub fn trans_closure(ccx: @mut CrateContext,
1810 decl: &ast::fn_decl,
1814 param_substs: Option<@param_substs>,
1816 attributes: &[ast::Attribute],
1818 maybe_load_env: &fn(@mut FunctionContext),
1819 finish: &fn(@mut Block)) {
1820 ccx.stats.n_closures += 1;
1821 let _icx = push_ctxt("trans_closure");
1822 set_uwtable(llfndecl);
1824 debug!("trans_closure(..., param_substs=%s)",
1825 param_substs.repr(ccx.tcx));
1827 // Set up arguments to the function.
1828 let fcx = new_fn_ctxt_w_id(ccx,
1837 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1839 // Set the fixed stack segment flag if necessary.
1840 if attr::contains_name(attributes, "fixed_stack_segment") {
1841 set_no_inline(fcx.llfn);
1842 set_fixed_stack_segment(fcx.llfn);
1845 // Create the first basic block in the function and keep a handle on it to
1846 // pass to finish_fn later.
1847 let bcx_top = fcx.entry_bcx.get();
1848 let mut bcx = bcx_top;
1849 let block_ty = node_id_type(bcx, body.id);
1851 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1852 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1854 maybe_load_env(fcx);
1856 // This call to trans_block is the place where we bridge between
1857 // translation calls that don't have a return value (trans_crate,
1858 // trans_mod, trans_item, et cetera) and those that do
1859 // (trans_block, trans_expr, et cetera).
1860 if body.expr.is_none() || ty::type_is_bot(block_ty) ||
1861 ty::type_is_nil(block_ty)
1863 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1865 let dest = expr::SaveIn(fcx.llretptr.get());
1866 bcx = controlflow::trans_block(bcx, body, dest);
1870 match fcx.llreturn {
1871 Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1872 None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1875 // Put return block after all other blocks.
1876 // This somewhat improves single-stepping experience in debugger.
1878 for &llreturn in fcx.llreturn.iter() {
1879 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1883 // Insert the mandatory first few basic blocks before lltop.
1884 finish_fn(fcx, bcx);
1887 // trans_fn: creates an LLVM function corresponding to a source language
1889 pub fn trans_fn(ccx: @mut CrateContext,
1891 decl: &ast::fn_decl,
1895 param_substs: Option<@param_substs>,
1897 attrs: &[ast::Attribute]) {
1899 let the_path_str = path_str(ccx.sess, path);
1900 let _s = StatRecorder::new(ccx, the_path_str);
1901 debug!("trans_fn(self_arg=%?, param_substs=%s)",
1903 param_substs.repr(ccx.tcx));
1904 let _icx = push_ctxt("trans_fn");
1905 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1917 if ccx.sess.opts.extra_debuginfo
1918 && fcx_has_nonzero_span(fcx) {
1919 debuginfo::create_function_metadata(fcx);
1925 fn insert_synthetic_type_entries(bcx: @mut Block,
1926 fn_args: &[ast::arg],
1930 * For tuple-like structs and enum-variants, we generate
1931 * synthetic AST nodes for the arguments. These have no types
1932 * in the type table and no entries in the moves table,
1933 * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
1934 * gets upset. This hack of a function bridges the gap by inserting types.
1936 * This feels horrible. I think we should just have a special path
1937 * for these functions and not try to use the generic code, but
1938 * that's not the problem I'm trying to solve right now. - nmatsakis
1941 let tcx = bcx.tcx();
1942 for i in range(0u, fn_args.len()) {
1943 debug!("setting type of argument %u (pat node %d) to %s",
1944 i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
1946 let pat_id = fn_args[i].pat.id;
1947 let arg_ty = arg_tys[i];
1948 tcx.node_types.insert(pat_id as uint, arg_ty);
1952 pub fn trans_enum_variant(ccx: @mut CrateContext,
1953 _enum_id: ast::NodeId,
1954 variant: &ast::variant,
1955 args: &[ast::variant_arg],
1957 param_substs: Option<@param_substs>,
1958 llfndecl: ValueRef) {
1959 let _icx = push_ctxt("trans_enum_variant");
1961 trans_enum_variant_or_tuple_like_struct(
1970 pub fn trans_tuple_struct(ccx: @mut CrateContext,
1971 fields: &[@ast::struct_field],
1972 ctor_id: ast::NodeId,
1973 param_substs: Option<@param_substs>,
1974 llfndecl: ValueRef) {
1975 let _icx = push_ctxt("trans_tuple_struct");
1977 trans_enum_variant_or_tuple_like_struct(
1987 fn id(&self) -> ast::NodeId;
1988 fn ty<'a>(&'a self) -> &'a ast::Ty;
1991 impl IdAndTy for ast::variant_arg {
1992 fn id(&self) -> ast::NodeId { self.id }
1993 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
1996 impl IdAndTy for @ast::struct_field {
1997 fn id(&self) -> ast::NodeId { self.node.id }
1998 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
2001 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2002 ccx: @mut CrateContext,
2003 ctor_id: ast::NodeId,
2006 param_substs: Option<@param_substs>,
2009 // Translate variant arguments to function arguments.
2010 let fn_args = do args.map |varg| {
2013 ty: (*varg.ty()).clone(),
2014 pat: ast_util::ident_to_pat(
2015 ccx.tcx.sess.next_node_id(),
2016 codemap::dummy_sp(),
2017 special_idents::arg),
2022 let no_substs: &[ty::t] = [];
2023 let ty_param_substs = match param_substs {
2024 Some(ref substs) => {
2025 let v: &[ty::t] = substs.tys;
2029 let v: &[ty::t] = no_substs;
2034 let ctor_ty = ty::subst_tps(ccx.tcx,
2037 ty::node_id_to_type(ccx.tcx, ctor_id));
2039 let result_ty = match ty::get(ctor_ty).sty {
2040 ty::ty_bare_fn(ref bft) => bft.sig.output,
2042 fmt!("trans_enum_variant_or_tuple_like_struct: \
2043 unexpected ctor return type %s",
2044 ty_to_str(ccx.tcx, ctor_ty)))
2047 let fcx = new_fn_ctxt_w_id(ccx,
2057 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2059 let bcx = fcx.entry_bcx.get();
2060 let arg_tys = ty::ty_fn_args(ctor_ty);
2062 insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2063 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2065 let repr = adt::represent_type(ccx, result_ty);
2066 adt::trans_start_init(bcx, repr, fcx.llretptr.get(), disr);
2067 for (i, fn_arg) in fn_args.iter().enumerate() {
2068 let lldestptr = adt::trans_field_ptr(bcx,
2073 let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2074 let arg_ty = arg_tys[i];
2075 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2077 finish_fn(fcx, bcx);
2080 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2081 id: ast::NodeId, vi: @~[@ty::VariantInfo],
2083 for variant in enum_definition.variants.iter() {
2084 let disr_val = vi[*i].disr_val;
2087 match variant.node.kind {
2088 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2089 let llfn = get_item_val(ccx, variant.node.id);
2090 trans_enum_variant(ccx, id, variant, *args,
2091 disr_val, None, llfn);
2093 ast::tuple_variant_kind(_) => {
2096 ast::struct_variant_kind(struct_def) => {
2097 trans_struct_def(ccx, struct_def);
2103 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2104 let _icx = push_ctxt("trans_item");
2105 let path = match ccx.tcx.items.get_copy(&item.id) {
2106 ast_map::node_item(_, p) => p,
2108 _ => fail!("trans_item"),
2111 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2112 if purity == ast::extern_fn {
2113 let llfndecl = get_item_val(ccx, item.id);
2114 foreign::trans_foreign_fn(ccx,
2115 vec::append((*path).clone(),
2116 [path_name(item.ident)]),
2121 } else if !generics.is_type_parameterized() {
2122 let llfndecl = get_item_val(ccx, item.id);
2124 vec::append((*path).clone(), [path_name(item.ident)]),
2133 for stmt in body.stmts.iter() {
2135 ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2144 ast::item_impl(ref generics, _, _, ref ms) => {
2145 meth::trans_impl(ccx,
2152 ast::item_mod(ref m) => {
2155 ast::item_enum(ref enum_definition, ref generics) => {
2156 if !generics.is_type_parameterized() {
2157 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2159 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2162 ast::item_static(_, m, expr) => {
2163 consts::trans_const(ccx, m, item.id);
2164 // Do static_assert checking. It can't really be done much earlier because we need to get
2165 // the value of the bool out of LLVM
2166 for attr in item.attrs.iter() {
2167 if "static_assert" == attr.name() {
2168 if m == ast::m_mutbl {
2169 ccx.sess.span_fatal(expr.span,
2170 "cannot have static_assert on a mutable static");
2172 let v = ccx.const_values.get_copy(&item.id);
2174 if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2175 ccx.sess.span_fatal(expr.span, "static assertion failed");
2181 ast::item_foreign_mod(ref foreign_mod) => {
2182 foreign::trans_foreign_mod(ccx, path, foreign_mod);
2184 ast::item_struct(struct_def, ref generics) => {
2185 if !generics.is_type_parameterized() {
2186 trans_struct_def(ccx, struct_def);
2189 _ => {/* fall through */ }
2193 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2194 // If this is a tuple-like struct, translate the constructor.
2195 match struct_def.ctor_id {
2196 // We only need to translate a constructor if there are fields;
2197 // otherwise this is a unit-like struct.
2198 Some(ctor_id) if struct_def.fields.len() > 0 => {
2199 let llfndecl = get_item_val(ccx, ctor_id);
2200 trans_tuple_struct(ccx, struct_def.fields,
2201 ctor_id, None, llfndecl);
2203 Some(_) | None => {}
2207 // Translate a module. Doing this amounts to translating the items in the
2208 // module; there ends up being no artifact (aside from linkage names) of
2209 // separate modules in the compiled program. That's because modules exist
2210 // only as a convenience for humans working with the code, to organize names
2211 // and control visibility.
2212 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2213 let _icx = push_ctxt("trans_mod");
2214 for item in m.items.iter() {
2215 trans_item(ccx, *item);
2219 pub fn register_fn(ccx: @mut CrateContext,
2222 node_id: ast::NodeId)
2224 let t = ty::node_id_to_type(ccx.tcx, node_id);
2225 register_fn_full(ccx, sp, sym, node_id, t)
2228 pub fn register_fn_full(ccx: @mut CrateContext,
2231 node_id: ast::NodeId,
2234 let llfty = type_of_fn_from_ty(ccx, node_type);
2235 register_fn_fuller(ccx, sp, sym, node_id, lib::llvm::CCallConv, llfty)
2238 pub fn register_fn_fuller(ccx: @mut CrateContext,
2241 node_id: ast::NodeId,
2242 cc: lib::llvm::CallConv,
2245 debug!("register_fn_fuller creating fn for item %d with path %s",
2247 ast_map::path_to_str(item_path(ccx, &node_id), token::get_ident_interner()));
2249 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty);
2250 ccx.item_symbols.insert(node_id, sym);
2252 // FIXME #4404 android JNI hacks
2253 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2254 (*ccx.sess.building_library &&
2255 ccx.sess.targ_cfg.os == session::os_android));
2257 create_entry_wrapper(ccx, sp, llfn);
2262 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2263 match *sess.entry_fn {
2264 Some((entry_id, _)) => node_id == entry_id,
2269 // Create a _rust_main(args: ~[str]) function which will be called from the
2270 // runtime rust_start function
2271 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2272 _sp: span, main_llfn: ValueRef) {
2273 let et = ccx.sess.entry_type.unwrap();
2274 if et == session::EntryMain {
2275 let llfn = create_main(ccx, main_llfn);
2276 create_entry_fn(ccx, llfn, true);
2278 create_entry_fn(ccx, main_llfn, false);
2281 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2282 let nt = ty::mk_nil();
2284 let llfty = type_of_fn(ccx, [], nt);
2285 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2286 lib::llvm::CCallConv, llfty);
2288 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2290 // the args vector built in create_entry_fn will need
2291 // be updated if this assertion starts to fail.
2292 assert!(fcx.has_immediate_return_value);
2294 let bcx = fcx.entry_bcx.get();
2296 let llenvarg = unsafe {
2297 let env_arg = fcx.env_arg_pos();
2298 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2300 let args = ~[llenvarg];
2301 Call(bcx, main_llfn, args);
2303 finish_fn(fcx, bcx);
2307 fn create_entry_fn(ccx: @mut CrateContext,
2308 rust_main: ValueRef,
2309 use_start_lang_item: bool) {
2310 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2313 // FIXME #4404 android JNI hacks
2314 let llfn = if *ccx.sess.building_library {
2315 decl_cdecl_fn(ccx.llmod, "amain", llfty)
2317 let main_name = match ccx.sess.targ_cfg.os {
2318 session::os_win32 => ~"WinMain@16",
2321 decl_cdecl_fn(ccx.llmod, main_name, llfty)
2323 let llbb = do "top".to_c_str().with_ref |buf| {
2325 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2328 let bld = ccx.builder.B;
2330 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2332 let crate_map = ccx.crate_map;
2333 let opaque_crate_map = do "crate_map".to_c_str().with_ref |buf| {
2334 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2337 let (start_fn, args) = if use_start_lang_item {
2338 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2340 Err(s) => { ccx.tcx.sess.fatal(s); }
2342 let start_fn = if start_def_id.crate == ast::LOCAL_CRATE {
2343 get_item_val(ccx, start_def_id.node)
2345 let start_fn_type = csearch::get_type(ccx.tcx,
2347 trans_external_path(ccx, start_def_id, start_fn_type)
2351 let opaque_rust_main = do "rust_main".to_c_str().with_ref |buf| {
2352 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2356 C_null(Type::opaque_box(ccx).ptr_to()),
2358 llvm::LLVMGetParam(llfn, 0),
2359 llvm::LLVMGetParam(llfn, 1),
2365 debug!("using user-defined start fn");
2367 C_null(Type::opaque_box(ccx).ptr_to()),
2368 llvm::LLVMGetParam(llfn, 0 as c_uint),
2369 llvm::LLVMGetParam(llfn, 1 as c_uint),
2376 let result = do args.as_imm_buf |buf, len| {
2377 llvm::LLVMBuildCall(bld, start_fn, buf, len as c_uint, noname())
2380 llvm::LLVMBuildRet(bld, result);
2385 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2386 llenvptr: ValueRef) {
2387 let ccx = bcx.ccx();
2388 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2389 Store(bcx, llfn, code_cell);
2390 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2391 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2392 Store(bcx, llenvblobptr, env_cell);
2395 pub fn item_path(ccx: &CrateContext, id: &ast::NodeId) -> path {
2396 match ccx.tcx.items.get_copy(id) {
2397 ast_map::node_item(i, p) =>
2398 vec::append((*p).clone(), [path_name(i.ident)]),
2399 // separate map for paths?
2400 _ => fail!("item_path")
2404 fn exported_name(ccx: @mut CrateContext, path: path, ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
2405 if attr::contains_name(attrs, "no_mangle") {
2406 path_elt_to_str(*path.last(), token::get_ident_interner())
2408 mangle_exported_name(ccx, path, ty)
2412 pub fn get_item_val(ccx: @mut CrateContext, id: ast::NodeId) -> ValueRef {
2413 debug!("get_item_val(id=`%?`)", id);
2415 let val = ccx.item_vals.find_copy(&id);
2419 let mut exprt = false;
2420 let item = ccx.tcx.items.get_copy(&id);
2421 let val = match item {
2422 ast_map::node_item(i, pth) => {
2424 let my_path = vec::append((*pth).clone(), [path_name(i.ident)]);
2425 let ty = ty::node_id_to_type(ccx.tcx, i.id);
2426 let sym = exported_name(ccx, my_path, ty, i.attrs);
2428 let v = match i.node {
2429 ast::item_static(_, m, expr) => {
2430 // We need the translated value here, because for enums the
2431 // LLVM type is not fully determined by the Rust type.
2432 let v = consts::const_expr(ccx, expr);
2433 ccx.const_values.insert(id, v);
2434 exprt = (m == ast::m_mutbl || i.vis == ast::public);
2437 let llty = llvm::LLVMTypeOf(v);
2438 let g = do sym.to_c_str().with_ref |buf| {
2439 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2442 ccx.item_symbols.insert(i.id, sym);
2447 ast::item_fn(_, purity, _, _, _) => {
2448 let llfn = if purity != ast::extern_fn {
2449 register_fn_full(ccx, i.span, sym, i.id, ty)
2451 foreign::register_foreign_fn(ccx, i.span, sym, i.id)
2453 set_inline_hint_if_appr(i.attrs, llfn);
2457 _ => fail!("get_item_val: weird result in table")
2460 match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2461 Some(sect) => unsafe {
2462 do sect.to_c_str().with_ref |buf| {
2463 llvm::LLVMSetSection(v, buf);
2472 ast_map::node_trait_method(trait_method, _, pth) => {
2473 debug!("get_item_val(): processing a node_trait_method");
2474 match *trait_method {
2475 ast::required(_) => {
2476 ccx.sess.bug("unexpected variant: required trait method in \
2479 ast::provided(m) => {
2481 register_method(ccx, id, pth, m)
2486 ast_map::node_method(m, _, pth) => {
2487 register_method(ccx, id, pth, m)
2490 ast_map::node_foreign_item(ni, _, _, pth) => {
2491 let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2495 ast::foreign_item_fn(*) => {
2496 let path = vec::append((*pth).clone(), [path_name(ni.ident)]);
2497 let sym = exported_name(ccx, path, ty, ni.attrs);
2499 register_fn_full(ccx, ni.span, sym, ni.id, ty)
2501 ast::foreign_item_static(*) => {
2502 let ident = token::ident_to_str(&ni.ident);
2503 let g = do ident.to_c_str().with_ref |buf| {
2505 let ty = type_of(ccx, ty);
2506 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2514 ast_map::node_variant(ref v, enm, pth) => {
2517 ast::tuple_variant_kind(ref args) => {
2518 assert!(args.len() != 0u);
2519 let pth = vec::append((*pth).clone(),
2520 [path_name(enm.ident),
2521 path_name((*v).node.name)]);
2522 let ty = ty::node_id_to_type(ccx.tcx, id);
2523 let sym = exported_name(ccx, pth, ty, enm.attrs);
2525 llfn = match enm.node {
2526 ast::item_enum(_, _) => {
2527 register_fn_full(ccx, (*v).span, sym, id, ty)
2529 _ => fail!("node_variant, shouldn't happen")
2532 ast::struct_variant_kind(_) => {
2533 fail!("struct variant kind unexpected in get_item_val")
2536 set_inline_hint(llfn);
2540 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2541 // Only register the constructor if this is a tuple-like struct.
2542 match struct_def.ctor_id {
2544 ccx.tcx.sess.bug("attempt to register a constructor of \
2545 a non-tuple-like struct")
2548 let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2549 let sym = exported_name(ccx, (*struct_path).clone(), ty,
2551 let llfn = register_fn_full(ccx, struct_item.span, sym, ctor_id, ty);
2552 set_inline_hint(llfn);
2559 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2564 if !exprt && !ccx.reachable.contains(&id) {
2565 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2568 ccx.item_vals.insert(id, val);
2574 pub fn register_method(ccx: @mut CrateContext,
2576 path: @ast_map::path,
2577 m: @ast::method) -> ValueRef {
2578 let mty = ty::node_id_to_type(ccx.tcx, id);
2580 let mut path = (*path).clone();
2581 path.push(path_name(gensym_name("meth")));
2582 path.push(path_name(m.ident));
2584 let sym = exported_name(ccx, path, mty, m.attrs);
2586 let llfn = register_fn_full(ccx, m.span, sym, id, mty);
2587 set_inline_hint_if_appr(m.attrs, llfn);
2591 // The constant translation pass.
2592 pub fn trans_constant(ccx: &mut CrateContext, it: @ast::item) {
2593 let _icx = push_ctxt("trans_constant");
2595 ast::item_enum(ref enum_definition, _) => {
2596 let vi = ty::enum_variants(ccx.tcx,
2597 ast::def_id { crate: ast::LOCAL_CRATE,
2600 let path = item_path(ccx, &it.id);
2601 for variant in (*enum_definition).variants.iter() {
2602 let p = vec::append(path.clone(), [
2603 path_name(variant.node.name),
2604 path_name(special_idents::descrim)
2606 let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2607 let disr_val = vi[i].disr_val;
2608 note_unique_llvm_symbol(ccx, s);
2609 let discrim_gvar = do s.to_c_str().with_ref |buf| {
2611 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2615 llvm::LLVMSetInitializer(discrim_gvar, C_uint(ccx, disr_val));
2616 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2618 ccx.discrims.insert(
2619 local_def(variant.node.id), discrim_gvar);
2620 ccx.discrim_symbols.insert(variant.node.id, s);
2628 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::Crate) {
2629 oldvisit::visit_crate(
2631 oldvisit::mk_simple_visitor(@oldvisit::SimpleVisitor {
2632 visit_item: |a| trans_constant(ccx, a),
2633 ..*oldvisit::default_simple_visitor()
2637 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2639 return PtrToInt(cx, v, ccx.int_type);
2642 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2644 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2649 ($name:expr, $args:expr, $ret:expr) => ({
2651 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2652 intrinsics.insert(name, f);
2656 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2657 let i8p = Type::i8p();
2658 let mut intrinsics = HashMap::new();
2660 ifn!("llvm.memcpy.p0i8.p0i8.i32",
2661 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2662 ifn!("llvm.memcpy.p0i8.p0i8.i64",
2663 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2664 ifn!("llvm.memmove.p0i8.p0i8.i32",
2665 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2666 ifn!("llvm.memmove.p0i8.p0i8.i64",
2667 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2668 ifn!("llvm.memset.p0i8.i32",
2669 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2670 ifn!("llvm.memset.p0i8.i64",
2671 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2673 ifn!("llvm.trap", [], Type::void());
2674 ifn!("llvm.frameaddress", [Type::i32()], i8p);
2676 ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2677 ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2678 ifn!("llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2679 ifn!("llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2681 ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2682 ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2683 ifn!("llvm.sin.f32", [Type::f32()], Type::f32());
2684 ifn!("llvm.sin.f64", [Type::f64()], Type::f64());
2685 ifn!("llvm.cos.f32", [Type::f32()], Type::f32());
2686 ifn!("llvm.cos.f64", [Type::f64()], Type::f64());
2687 ifn!("llvm.exp.f32", [Type::f32()], Type::f32());
2688 ifn!("llvm.exp.f64", [Type::f64()], Type::f64());
2689 ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2690 ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2691 ifn!("llvm.log.f32", [Type::f32()], Type::f32());
2692 ifn!("llvm.log.f64", [Type::f64()], Type::f64());
2693 ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2694 ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2695 ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2696 ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2698 ifn!("llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2699 ifn!("llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2701 ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2702 ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2703 ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2704 ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2705 ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2706 ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2707 ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2708 ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2710 ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2711 ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2712 ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2713 ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2715 ifn!("llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2716 ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2717 ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2718 ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2720 ifn!("llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2721 ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2722 ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2723 ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2725 ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2726 ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2727 ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2732 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2733 ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2734 ifn!("llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2737 pub fn trap(bcx: @mut Block) {
2738 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2739 Some(&x) => { Call(bcx, x, []); },
2740 _ => bcx.sess().bug("unbound llvm.trap in trap")
2744 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2745 if !ccx.sess.opts.gc || !ccx.uses_gc {
2749 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2750 let gc_metadata = do gc_metadata_name.to_c_str().with_ref |buf| {
2752 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2756 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2757 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2758 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2762 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2763 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2764 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2765 let map = do "_rust_mod_map".to_c_str().with_ref |buf| {
2767 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2770 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2771 let mut elts: ~[ValueRef] = ~[];
2773 // This is not ideal, but the borrow checker doesn't
2774 // like the multiple borrows. At least, it doesn't
2775 // like them on the current snapshot. (2013-06-14)
2777 for (k, _) in ccx.module_data.iter() {
2778 keys.push(k.to_managed());
2781 for key in keys.iter() {
2782 let val = *ccx.module_data.find_equiv(key).get();
2783 let s_const = C_cstr(ccx, *key);
2784 let s_ptr = p2i(ccx, s_const);
2785 let v_ptr = p2i(ccx, val);
2786 let elt = C_struct([s_ptr, v_ptr]);
2789 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2792 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2798 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2799 llmod: ModuleRef) -> ValueRef {
2800 let targ_cfg = sess.targ_cfg;
2801 let int_type = Type::int(targ_cfg.arch);
2802 let mut n_subcrates = 1;
2803 let cstore = sess.cstore;
2804 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2805 let mapname = if *sess.building_library {
2806 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2810 let sym_name = ~"_rust_crate_map_" + mapname;
2811 let arrtype = Type::array(&int_type, n_subcrates as u64);
2812 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2813 let map = do sym_name.to_c_str().with_ref |buf| {
2815 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2818 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2822 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2823 let mut subcrates: ~[ValueRef] = ~[];
2825 let cstore = ccx.sess.cstore;
2826 while cstore::have_crate_data(cstore, i) {
2827 let cdata = cstore::get_crate_data(cstore, i);
2828 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2830 cstore::get_crate_vers(cstore, i),
2831 cstore::get_crate_hash(cstore, i));
2832 let cr = do nm.to_c_str().with_ref |buf| {
2834 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2837 subcrates.push(p2i(ccx, cr));
2840 subcrates.push(C_int(ccx, 0));
2842 let llannihilatefn = match ccx.tcx.lang_items.annihilate_fn() {
2843 Some(annihilate_def_id) => {
2844 if annihilate_def_id.crate == ast::LOCAL_CRATE {
2845 get_item_val(ccx, annihilate_def_id.node)
2847 let annihilate_fn_type = csearch::get_type(ccx.tcx,
2848 annihilate_def_id).ty;
2849 trans_external_path(ccx, annihilate_def_id, annihilate_fn_type)
2852 None => { C_null(Type::i8p()) }
2856 let mod_map = create_module_map(ccx);
2857 llvm::LLVMSetInitializer(map, C_struct(
2859 lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2861 C_array(ccx.int_type, subcrates)]));
2865 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2866 -> encoder::EncodeParams<'r> {
2868 let diag = cx.sess.diagnostic();
2869 let item_symbols = &cx.item_symbols;
2870 let discrim_symbols = &cx.discrim_symbols;
2871 let link_meta = &cx.link_meta;
2872 encoder::EncodeParams {
2875 reexports2: cx.exp_map2,
2876 item_symbols: item_symbols,
2877 discrim_symbols: discrim_symbols,
2878 link_meta: link_meta,
2879 cstore: cx.sess.cstore,
2880 encode_inlined_item: ie,
2881 reachable: cx.reachable,
2885 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) {
2886 if !*cx.sess.building_library { return; }
2888 let encode_inlined_item: encoder::encode_inlined_item =
2889 |ecx, ebml_w, path, ii|
2890 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2892 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2893 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2894 let llconst = C_struct([llmeta]);
2895 let mut llglobal = do "rust_metadata".to_c_str().with_ref |buf| {
2897 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2901 llvm::LLVMSetInitializer(llglobal, llconst);
2902 do cx.sess.targ_cfg.target_strs.meta_sect_name.to_c_str().with_ref |buf| {
2903 llvm::LLVMSetSection(llglobal, buf)
2905 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2907 let t_ptr_i8 = Type::i8p();
2908 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2909 let llvm_used = do "llvm.used".to_c_str().with_ref |buf| {
2910 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2912 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2913 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2917 fn mk_global(ccx: &CrateContext,
2923 let llglobal = do name.to_c_str().with_ref |buf| {
2924 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
2926 llvm::LLVMSetInitializer(llglobal, llval);
2927 llvm::LLVMSetGlobalConstant(llglobal, True);
2930 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2937 // Writes the current ABI version into the crate.
2938 pub fn write_abi_version(ccx: &mut CrateContext) {
2939 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
2942 pub fn trans_crate(sess: session::Session,
2944 analysis: &CrateAnalysis,
2945 output: &Path) -> CrateTranslation {
2946 // Before we touch LLVM, make sure that multithreading is enabled.
2947 if unsafe { !llvm::LLVMRustStartMultithreading() } {
2948 //sess.bug("couldn't enable multi-threaded LLVM");
2951 let mut symbol_hasher = hash::default_state();
2952 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
2954 // Append ".rc" to crate name as LLVM module identifier.
2956 // LLVM code generator emits a ".file filename" directive
2957 // for ELF backends. Value of the "filename" is set as the
2958 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2959 // crashes if the module identifer is same as other symbols
2960 // such as a function name in the module.
2961 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2962 let llmod_id = link_meta.name.to_owned() + ".rc";
2964 let ccx = @mut CrateContext::new(sess,
2971 analysis.reachable);
2974 let _icx = push_ctxt("data");
2975 trans_constants(ccx, crate);
2979 let _icx = push_ctxt("text");
2980 trans_mod(ccx, &crate.module);
2983 decl_gc_metadata(ccx, llmod_id);
2984 fill_crate_map(ccx, ccx.crate_map);
2985 glue::emit_tydescs(ccx);
2986 write_abi_version(ccx);
2987 if ccx.sess.opts.debuginfo {
2988 debuginfo::finalize(ccx);
2991 // Translate the metadata.
2992 write_metadata(ccx, crate);
2993 if ccx.sess.trans_stats() {
2994 io::println("--- trans stats ---");
2995 printfln!("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
2996 printfln!("n_glues_created: %u", ccx.stats.n_glues_created);
2997 printfln!("n_null_glues: %u", ccx.stats.n_null_glues);
2998 printfln!("n_real_glues: %u", ccx.stats.n_real_glues);
3000 printfln!("n_fns: %u", ccx.stats.n_fns);
3001 printfln!("n_monos: %u", ccx.stats.n_monos);
3002 printfln!("n_inlines: %u", ccx.stats.n_inlines);
3003 printfln!("n_closures: %u", ccx.stats.n_closures);
3004 io::println("fn stats:");
3005 do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3008 for tuple in ccx.stats.fn_stats.iter() {
3010 (ref name, ms, insns) => {
3011 printfln!("%u insns, %u ms, %s", insns, ms, *name);
3016 if ccx.sess.count_llvm_insns() {
3017 for (k, v) in ccx.stats.llvm_insns.iter() {
3018 printfln!("%-7u %s", *v, *k);
3022 let llcx = ccx.llcx;
3023 let link_meta = ccx.link_meta;
3024 let llmod = ccx.llmod;
3026 return CrateTranslation {