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 lib::llvm::{ContextRef, ModuleRef, ValueRef, BasicBlockRef};
32 use lib::llvm::{llvm, True};
34 use metadata::common::LinkMeta;
35 use metadata::{csearch, cstore, encoder};
36 use middle::astencode;
37 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
38 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;
69 use std::hashmap::{HashMap, HashSet};
72 use std::libc::c_uint;
79 use syntax::ast::ident;
80 use syntax::ast_map::{path, path_elt_to_str, path_name};
81 use syntax::ast_util::{local_def};
83 use syntax::attr::AttrMetaMethods;
84 use syntax::codemap::span;
85 use syntax::parse::token;
86 use syntax::parse::token::{special_idents};
87 use syntax::print::pprust::stmt_to_str;
89 use syntax::{ast, ast_util, codemap, ast_map};
90 use syntax::abi::{X86, X86_64, Arm, Mips};
92 pub use middle::trans::context::task_llcx;
94 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
96 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
97 let opt = local_data::get(task_local_insn_key, |k| k.map(|&k| *k));
103 pub fn init_insn_ctxt() {
104 local_data::set(task_local_insn_key, @~[]);
107 pub struct _InsnCtxt { _x: () }
110 impl Drop for _InsnCtxt {
112 do local_data::modify(task_local_insn_key) |c| {
113 do c.map_consume |ctx| {
114 let mut ctx = (*ctx).clone();
122 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
123 debug!("new InsnCtxt: %s", s);
124 do local_data::modify(task_local_insn_key) |c| {
125 do c.map_consume |ctx| {
126 let mut ctx = (*ctx).clone();
134 fn fcx_has_nonzero_span(fcx: &FunctionContext) -> bool {
137 Some(span) => *span.lo != 0 || *span.hi != 0
141 struct StatRecorder<'self> {
142 ccx: @mut CrateContext,
148 impl<'self> StatRecorder<'self> {
149 pub fn new(ccx: @mut CrateContext,
150 name: &'self str) -> StatRecorder<'self> {
151 let start = if ccx.sess.trans_stats() {
152 time::precise_time_ns()
156 let istart = ccx.stats.n_llvm_insns;
167 impl<'self> Drop for StatRecorder<'self> {
169 if self.ccx.sess.trans_stats() {
170 let end = time::precise_time_ns();
171 let elapsed = ((end - self.start) / 1_000_000) as uint;
172 let iend = self.ccx.stats.n_llvm_insns;
173 self.ccx.stats.fn_stats.push((self.name.to_owned(),
175 iend - self.istart));
176 self.ccx.stats.n_fns += 1;
177 // Reset LLVM insn count to avoid compound costs.
178 self.ccx.stats.n_llvm_insns = self.istart;
183 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
184 let llfn: ValueRef = do name.as_c_str |buf| {
186 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
190 lib::llvm::SetFunctionCallConv(llfn, cc);
194 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
195 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
198 // Only use this if you are going to actually define the function. It's
199 // not valid to simply declare a function as internal.
200 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
201 let llfn = decl_cdecl_fn(llmod, name, ty);
202 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
206 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
207 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
208 match externs.find_copy(&name) {
212 let f = decl_fn(llmod, name, cc, ty);
213 externs.insert(name, f);
217 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
218 name: @str, ty: Type) -> ValueRef {
219 match externs.find_copy(&name) {
224 let c = do name.as_c_str |buf| {
225 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
227 externs.insert(name, c);
231 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
232 let _icx = push_ctxt("umax");
233 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
234 return Select(cx, cond, b, a);
237 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
238 let _icx = push_ctxt("umin");
239 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
240 return Select(cx, cond, a, b);
243 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
244 // The type of the returned pointer is always i8*. If you care about the
245 // return type, use bump_ptr().
246 pub fn ptr_offs(bcx: @mut Block, base: ValueRef, sz: ValueRef) -> ValueRef {
247 let _icx = push_ctxt("ptr_offs");
248 let raw = PointerCast(bcx, base, Type::i8p());
249 InBoundsGEP(bcx, raw, [sz])
252 // Increment a pointer by a given amount and then cast it to be a pointer
254 pub fn bump_ptr(bcx: @mut Block, t: ty::t, base: ValueRef, sz: ValueRef) ->
256 let _icx = push_ctxt("bump_ptr");
258 let bumped = ptr_offs(bcx, base, sz);
259 let typ = type_of(ccx, t).ptr_to();
260 PointerCast(bcx, bumped, typ)
263 // Returns a pointer to the body for the box. The box may be an opaque
264 // box. The result will be casted to the type of body_t, if it is statically
267 // The runtime equivalent is box_body() in "rust_internal.h".
268 pub fn opaque_box_body(bcx: @mut Block,
270 boxptr: ValueRef) -> ValueRef {
271 let _icx = push_ctxt("opaque_box_body");
273 let ty = type_of(ccx, body_t);
274 let ty = Type::box(ccx, &ty);
275 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
276 GEPi(bcx, boxptr, [0u, abi::box_field_body])
279 // malloc_raw_dyn: allocates a box to contain a given type, but with a
280 // potentially dynamic size.
281 pub fn malloc_raw_dyn(bcx: @mut Block,
284 size: ValueRef) -> Result {
285 let _icx = push_ctxt("malloc_raw");
288 fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::def_id {
289 let li = &bcx.tcx().lang_items;
290 match li.require(it) {
293 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
294 bcx.ty_to_str(t), s));
299 if heap == heap_exchange {
300 let llty_value = type_of::type_of(ccx, t);
304 let r = callee::trans_lang_call(
306 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
309 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
311 // we treat ~fn, @fn and @[] as @ here, which isn't ideal
312 let (mk_fn, langcall) = match heap {
313 heap_managed | heap_managed_unique => {
315 require_alloc_fn(bcx, t, MallocFnLangItem))
317 heap_exchange_closure => {
319 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
321 _ => fail!("heap_exchange already handled")
324 // Grab the TypeRef type of box_ptr_ty.
325 let box_ptr_ty = mk_fn(bcx.tcx(), t);
326 let llty = type_of(ccx, box_ptr_ty);
328 // Get the tydesc for the body:
329 let static_ti = get_tydesc(ccx, t);
330 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
333 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
334 let r = callee::trans_lang_call(
339 let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
340 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
345 // malloc_raw: expects an unboxed type and returns a pointer to
346 // enough space for a box of that type. This includes a rust_opaque_box
348 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
349 let ty = type_of(bcx.ccx(), t);
350 let size = llsize_of(bcx.ccx(), ty);
351 malloc_raw_dyn(bcx, t, heap, size)
354 pub struct MallocResult {
360 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
361 // and pulls out the body
362 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
364 assert!(heap != heap_exchange);
365 let _icx = push_ctxt("malloc_general");
366 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
367 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
369 MallocResult { bcx: bcx, box: llbox, body: body }
372 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
373 let ty = type_of(bcx.ccx(), t);
374 assert!(heap != heap_exchange);
375 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
377 pub fn malloc_boxed(bcx: @mut Block, t: ty::t)
379 malloc_general(bcx, t, heap_managed)
382 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
383 if ty::type_contents(bcx.tcx(), t).contains_managed() {
390 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
391 assert!(heap != heap_exchange);
392 if heap == heap_managed_unique {
393 // In cases where we are looking at a unique-typed allocation in the
394 // managed heap (thus have refcount 1 from the managed allocator),
395 // such as a ~(@foo) or such. These need to have their refcount forced
396 // to -2 so the annihilator ignores them.
397 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
398 let rc_val = C_int(bcx.ccx(), -2);
399 Store(bcx, rc_val, rc);
403 // Type descriptor and type glue stuff
405 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
406 get_tydesc(ccx, t).tydesc
409 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
410 match ccx.tydescs.find(&t) {
417 ccx.stats.n_static_tydescs += 1u;
418 let inf = glue::declare_tydesc(ccx, t);
419 ccx.tydescs.insert(t, inf);
423 pub fn set_optimize_for_size(f: ValueRef) {
425 llvm::LLVMAddFunctionAttr(f,
426 lib::llvm::OptimizeForSizeAttribute
432 pub fn set_no_inline(f: ValueRef) {
434 llvm::LLVMAddFunctionAttr(f,
435 lib::llvm::NoInlineAttribute as c_uint,
440 pub fn set_no_unwind(f: ValueRef) {
442 llvm::LLVMAddFunctionAttr(f,
443 lib::llvm::NoUnwindAttribute as c_uint,
448 // Tell LLVM to emit the information necessary to unwind the stack for the
450 pub fn set_uwtable(f: ValueRef) {
452 llvm::LLVMAddFunctionAttr(f,
453 lib::llvm::UWTableAttribute as c_uint,
458 pub fn set_inline_hint(f: ValueRef) {
460 llvm::LLVMAddFunctionAttr(f,
461 lib::llvm::InlineHintAttribute as c_uint,
466 pub fn set_inline_hint_if_appr(attrs: &[ast::Attribute],
469 match find_inline_attr(attrs) {
470 InlineHint => set_inline_hint(llfn),
471 InlineAlways => set_always_inline(llfn),
472 InlineNever => set_no_inline(llfn),
473 InlineNone => { /* fallthrough */ }
477 pub fn set_always_inline(f: ValueRef) {
479 llvm::LLVMAddFunctionAttr(f,
480 lib::llvm::AlwaysInlineAttribute as c_uint,
485 pub fn set_fixed_stack_segment(f: ValueRef) {
487 llvm::LLVMAddFunctionAttr(f, 0, 1 << (39 - 32));
491 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
492 if ty::type_is_structural(t) {
493 set_optimize_for_size(f);
494 } else { set_always_inline(f); }
497 // Double-check that we never ask LLVM to declare the same symbol twice. It
498 // silently mangles such symbols, breaking our linkage model.
499 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
500 if ccx.all_llvm_symbols.contains(&sym) {
501 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
503 ccx.all_llvm_symbols.insert(sym);
507 pub fn get_res_dtor(ccx: @mut CrateContext,
509 parent_id: ast::def_id,
512 let _icx = push_ctxt("trans_res_dtor");
513 if !substs.is_empty() {
514 let did = if did.crate != ast::local_crate {
515 inline::maybe_instantiate_inline(ccx, did)
519 assert_eq!(did.crate, ast::local_crate);
520 let tsubsts = ty::substs { self_r: None, self_ty: None,
521 tps: /*bad*/ substs.to_owned() };
522 let (val, _) = monomorphize::monomorphic_fn(ccx,
530 } else if did.crate == ast::local_crate {
531 get_item_val(ccx, did.node)
534 let name = csearch::get_symbol(ccx.sess.cstore, did);
535 let class_ty = ty::subst_tps(tcx,
538 ty::lookup_item_type(tcx, parent_id).ty);
539 let llty = type_of_dtor(ccx, class_ty);
540 let name = name.to_managed(); // :-(
541 get_extern_fn(&mut ccx.externs,
544 lib::llvm::CCallConv,
549 // Structural comparison: a rather involved form of glue.
550 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
551 if cx.sess.opts.save_temps {
552 let _: () = str::as_c_str(s, |buf| {
554 llvm::LLVMSetValueName(v, buf)
561 // Used only for creating scalar comparison glue.
562 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
564 // NB: This produces an i1, not a Rust bool (i8).
565 pub fn compare_scalar_types(cx: @mut Block,
571 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
573 match ty::get(t).sty {
574 ty::ty_nil => rslt(cx, f(nil_type)),
575 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
576 ty::ty_int(_) => rslt(cx, f(signed_int)),
577 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
578 ty::ty_float(_) => rslt(cx, f(floating_point)),
581 controlflow::trans_fail(
583 @"attempt to compare values of type type"),
587 // Should never get here, because t is scalar.
588 cx.sess().bug("non-scalar type passed to \
589 compare_scalar_types")
595 // A helper function to do the actual comparison of scalar values.
596 pub fn compare_scalar_values(cx: @mut Block,
602 let _icx = push_ctxt("compare_scalar_values");
603 fn die(cx: @mut Block) -> ! {
604 cx.tcx().sess.bug("compare_scalar_values: must be a\
605 comparison operator");
609 // We don't need to do actual comparisons for nil.
610 // () == () holds but () < () does not.
612 ast::eq | ast::le | ast::ge => return C_i1(true),
613 ast::ne | ast::lt | ast::gt => return C_i1(false),
614 // refinements would be nice
620 ast::eq => lib::llvm::RealOEQ,
621 ast::ne => lib::llvm::RealUNE,
622 ast::lt => lib::llvm::RealOLT,
623 ast::le => lib::llvm::RealOLE,
624 ast::gt => lib::llvm::RealOGT,
625 ast::ge => lib::llvm::RealOGE,
628 return FCmp(cx, cmp, lhs, rhs);
632 ast::eq => lib::llvm::IntEQ,
633 ast::ne => lib::llvm::IntNE,
634 ast::lt => lib::llvm::IntSLT,
635 ast::le => lib::llvm::IntSLE,
636 ast::gt => lib::llvm::IntSGT,
637 ast::ge => lib::llvm::IntSGE,
640 return ICmp(cx, cmp, lhs, rhs);
644 ast::eq => lib::llvm::IntEQ,
645 ast::ne => lib::llvm::IntNE,
646 ast::lt => lib::llvm::IntULT,
647 ast::le => lib::llvm::IntULE,
648 ast::gt => lib::llvm::IntUGT,
649 ast::ge => lib::llvm::IntUGE,
652 return ICmp(cx, cmp, lhs, rhs);
657 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
659 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
660 return Load(cx, GEPi(cx, p, idxs));
663 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
664 Store(cx, v, GEPi(cx, p, idxs));
667 // Iterates through the elements of a structural type.
668 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
669 f: val_and_ty_fn) -> @mut Block {
670 let _icx = push_ctxt("iter_structural_ty");
672 fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
673 variant: @ty::VariantInfo,
674 tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
675 let _icx = push_ctxt("iter_variant");
679 for variant.args.iter().enumerate().advance |(i, &arg)| {
681 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
682 ty::subst_tps(tcx, tps, None, arg));
688 match ty::get(t).sty {
689 ty::ty_struct(*) => {
690 let repr = adt::represent_type(cx.ccx(), t);
691 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
692 for field_tys.iter().enumerate().advance |(i, field_ty)| {
693 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
694 cx = f(cx, llfld_a, field_ty.mt.ty);
698 ty::ty_estr(ty::vstore_fixed(_)) |
699 ty::ty_evec(_, ty::vstore_fixed(_)) => {
700 let (base, len) = tvec::get_base_and_len(cx, av, t);
701 cx = tvec::iter_vec_raw(cx, base, t, len, f);
703 ty::ty_tup(ref args) => {
704 let repr = adt::represent_type(cx.ccx(), t);
705 for args.iter().enumerate().advance |(i, arg)| {
706 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
707 cx = f(cx, llfld_a, *arg);
710 ty::ty_enum(tid, ref substs) => {
713 let repr = adt::represent_type(ccx, t);
714 let variants = ty::enum_variants(ccx.tcx, tid);
715 let n_variants = (*variants).len();
717 // NB: we must hit the discriminant first so that structural
718 // comparison know not to proceed when the discriminants differ.
720 match adt::trans_switch(cx, repr, av) {
721 (_match::single, None) => {
722 cx = iter_variant(cx, repr, av, variants[0],
725 (_match::switch, Some(lldiscrim_a)) => {
726 cx = f(cx, lldiscrim_a, ty::mk_int());
727 let unr_cx = sub_block(cx, "enum-iter-unr");
729 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
731 let next_cx = sub_block(cx, "enum-iter-next");
733 for (*variants).iter().advance |variant| {
735 sub_block(cx, ~"enum-iter-variant-" +
736 int::to_str(variant.disr_val));
738 iter_variant(variant_cx, repr, av, *variant,
739 substs.tps, |x,y,z| f(x,y,z));
740 match adt::trans_case(cx, repr, variant.disr_val) {
741 _match::single_result(r) => {
742 AddCase(llswitch, r.val, variant_cx.llbb)
744 _ => ccx.sess.unimpl("value from adt::trans_case \
745 in iter_structural_ty")
747 Br(variant_cx, next_cx.llbb);
751 _ => ccx.sess.unimpl("value from adt::trans_switch \
752 in iter_structural_ty")
755 _ => cx.sess().unimpl("type in iter_structural_ty")
760 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::binop,
761 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
762 cast_shift_rhs(op, lhs, rhs,
763 |a,b| Trunc(cx, a, b),
764 |a,b| ZExt(cx, a, b))
767 pub fn cast_shift_const_rhs(op: ast::binop,
768 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
769 cast_shift_rhs(op, lhs, rhs,
770 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
771 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
774 pub fn cast_shift_rhs(op: ast::binop,
775 lhs: ValueRef, rhs: ValueRef,
776 trunc: &fn(ValueRef, Type) -> ValueRef,
777 zext: &fn(ValueRef, Type) -> ValueRef)
779 // Shifts may have any size int on the rhs
781 if ast_util::is_shift_binop(op) {
782 let rhs_llty = val_ty(rhs);
783 let lhs_llty = val_ty(lhs);
784 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
785 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
788 } else if lhs_sz > rhs_sz {
789 // FIXME (#1877: If shifting by negative
790 // values becomes not undefined then this is wrong.
801 pub fn fail_if_zero(cx: @mut Block, span: span, divrem: ast::binop,
802 rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
803 let text = if divrem == ast::div {
804 @"attempted to divide by zero"
806 @"attempted remainder with a divisor of zero"
808 let is_zero = match ty::get(rhs_t).sty {
810 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
811 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
814 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
815 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
818 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
819 ty_to_str(cx.ccx().tcx, rhs_t));
822 do with_cond(cx, is_zero) |bcx| {
823 controlflow::trans_fail(bcx, Some(span), text)
827 pub fn null_env_ptr(bcx: @mut Block) -> ValueRef {
828 C_null(Type::opaque_box(bcx.ccx()).ptr_to())
831 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
833 let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
834 match ty::get(t).sty {
835 ty::ty_bare_fn(_) | ty::ty_closure(_) => {
836 let llty = type_of_fn_from_ty(ccx, t);
837 return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
838 lib::llvm::CCallConv, llty);
841 let llty = type_of(ccx, t);
842 return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
847 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef])
848 -> (ValueRef, @mut Block) {
849 let _icx = push_ctxt("invoke_");
851 return (C_null(Type::i8()), bcx);
854 match bcx.node_info {
855 None => debug!("invoke at ???"),
857 debug!("invoke at %s",
858 bcx.sess().codemap.span_to_str(node_info.span));
862 if need_invoke(bcx) {
864 debug!("invoking %x at %x",
865 ::std::cast::transmute(llfn),
866 ::std::cast::transmute(bcx.llbb));
867 for llargs.iter().advance |&llarg| {
868 debug!("arg: %x", ::std::cast::transmute(llarg));
871 let normal_bcx = sub_block(bcx, "normal return");
872 let llresult = Invoke(bcx,
876 get_landing_pad(bcx));
877 return (llresult, normal_bcx);
880 debug!("calling %x at %x",
881 ::std::cast::transmute(llfn),
882 ::std::cast::transmute(bcx.llbb));
883 for llargs.iter().advance |&llarg| {
884 debug!("arg: %x", ::std::cast::transmute(llarg));
887 let llresult = Call(bcx, llfn, llargs);
888 return (llresult, bcx);
892 pub fn need_invoke(bcx: @mut Block) -> bool {
893 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
897 // Avoid using invoke if we are already inside a landing pad.
902 if have_cached_lpad(bcx) {
906 // Walk the scopes to look for cleanups
908 let mut cur_scope = cur.scope;
910 cur_scope = match cur_scope {
912 for inf.cleanups.iter().advance |cleanup| {
914 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
915 if cleanup_type == normal_exit_and_unwind {
924 cur = match cur.parent {
934 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
936 do in_lpad_scope_cx(bcx) |inf| {
937 match inf.landing_pad {
938 Some(_) => res = true,
945 pub fn in_lpad_scope_cx(bcx: @mut Block, f: &fn(si: &mut ScopeInfo)) {
947 let mut cur_scope = bcx.scope;
949 cur_scope = match cur_scope {
951 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
958 bcx = block_parent(bcx);
965 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
966 let _icx = push_ctxt("get_landing_pad");
968 let mut cached = None;
969 let mut pad_bcx = bcx; // Guaranteed to be set below
970 do in_lpad_scope_cx(bcx) |inf| {
971 // If there is a valid landing pad still around, use it
972 match inf.landing_pad {
973 Some(target) => cached = Some(target),
975 pad_bcx = lpad_block(bcx, "unwind");
976 inf.landing_pad = Some(pad_bcx.llbb);
980 // Can't return from block above
981 match cached { Some(b) => return b, None => () }
982 // The landing pad return type (the type being propagated). Not sure what
983 // this represents but it's determined by the personality function and
984 // this is what the EH proposal example uses.
985 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
986 // The exception handling personality function. This is the C++
987 // personality function __gxx_personality_v0, wrapped in our naming
989 let personality = bcx.ccx().upcalls.rust_personality;
990 // The only landing pad clause will be 'cleanup'
991 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
992 // The landing pad block is a cleanup
993 SetCleanup(pad_bcx, llretval);
995 // Because we may have unwound across a stack boundary, we must call into
996 // the runtime to figure out which stack segment we are on and place the
997 // stack limit back into the TLS.
998 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
1000 // We store the retval in a function-central alloca, so that calls to
1001 // Resume can find it.
1002 match bcx.fcx.personality {
1003 Some(addr) => Store(pad_bcx, llretval, addr),
1005 let addr = alloca(pad_bcx, val_ty(llretval), "");
1006 bcx.fcx.personality = Some(addr);
1007 Store(pad_bcx, llretval, addr);
1011 // Unwind all parent scopes, and finish with a Resume instr
1012 cleanup_and_leave(pad_bcx, None, None);
1013 return pad_bcx.llbb;
1016 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::node_id) -> @mut Block {
1017 let mut bcx_sid = bcx;
1018 let mut cur_scope = bcx_sid.scope;
1020 cur_scope = match cur_scope {
1022 match inf.node_info {
1023 Some(NodeInfo { id, _ }) if id == scope_id => {
1026 // FIXME(#6268, #6248) hacky cleanup for nested method calls
1027 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1034 bcx_sid = match bcx_sid.parent {
1035 None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1036 Some(bcx_par) => bcx_par
1045 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1046 if ty::type_is_bot(t) {
1047 return C_null(Type::i8p());
1049 let llptr = alloc_ty(bcx, t, "");
1050 Store(bcx, v, llptr);
1054 // Since this function does *not* root, it is the caller's responsibility to
1055 // ensure that the referent is pointed to by a root.
1056 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1057 let llptr = alloca(cx, val_ty(v), "");
1058 Store(cx, v, llptr);
1062 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1063 let _icx = push_ctxt("spill_if_immediate");
1064 if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1068 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1069 let _icx = push_ctxt("load_if_immediate");
1070 if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1074 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<span>, trace_str: @str) {
1075 if !bcx.sess().trace() { return; }
1076 let _icx = push_ctxt("trans_trace");
1077 add_comment(bcx, trace_str);
1078 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1079 let (V_filename, V_line) = match sp_opt {
1081 let sess = bcx.sess();
1082 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1083 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1086 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1089 let ccx = bcx.ccx();
1090 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1091 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1092 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1093 Call(bcx, ccx.upcalls.trace, args);
1096 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1097 match local.pat.node {
1098 ast::pat_wild => true, _ => false
1102 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1104 debug!("init_local(bcx=%s, local.id=%?)",
1105 bcx.to_str(), local.id);
1106 let _indenter = indenter();
1108 let _icx = push_ctxt("init_local");
1110 if ignore_lhs(bcx, local) {
1111 // Handle let _ = e; just like e;
1114 return expr::trans_into(bcx, init, expr::Ignore);
1116 None => { return bcx; }
1120 _match::store_local(bcx, local.pat, local.init)
1123 pub fn trans_stmt(cx: @mut Block, s: &ast::stmt) -> @mut Block {
1124 let _icx = push_ctxt("trans_stmt");
1125 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1127 if cx.sess().asm_comments() {
1128 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1132 debuginfo::update_source_pos(cx, s.span);
1135 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1136 bcx = expr::trans_into(cx, e, expr::Ignore);
1138 ast::stmt_decl(d, _) => {
1140 ast::decl_local(ref local) => {
1141 bcx = init_local(bcx, *local);
1142 if cx.sess().opts.extra_debuginfo
1143 && fcx_has_nonzero_span(bcx.fcx) {
1144 debuginfo::create_local_var_metadata(bcx, *local);
1147 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1150 ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1156 // You probably don't want to use this one. See the
1157 // next three functions instead.
1158 pub fn new_block(cx: @mut FunctionContext,
1159 parent: Option<@mut Block>,
1160 scope: Option<@mut ScopeInfo>,
1163 opt_node_info: Option<NodeInfo>)
1166 let llbb = do name.as_c_str |buf| {
1167 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1169 let bcx = @mut Block::new(llbb,
1175 for parent.iter().advance |cx| {
1185 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1186 node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1194 node_info: node_info,
1198 // Use this when you're at the top block of a function or the like.
1199 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1201 return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1202 "function top level", opt_node_info);
1205 pub fn scope_block(bcx: @mut Block,
1206 opt_node_info: Option<NodeInfo>,
1207 n: &str) -> @mut Block {
1208 return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1212 pub fn loop_scope_block(bcx: @mut Block,
1213 loop_break: @mut Block,
1214 loop_label: Option<ident>,
1216 opt_node_info: Option<NodeInfo>) -> @mut Block {
1217 return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1219 loop_break: Some(loop_break),
1220 loop_label: loop_label,
1224 node_info: opt_node_info,
1225 }), bcx.is_lpad, n, opt_node_info);
1228 // Use this when creating a block for the inside of a landing pad.
1229 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1230 new_block(bcx.fcx, Some(bcx), None, true, n, None)
1233 // Use this when you're making a general CFG BB within a scope.
1234 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1235 new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1238 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1239 @mut Block::new(llbb, None, is_lpad, None, fcx)
1243 // trans_block_cleanups: Go through all the cleanups attached to this
1244 // block and execute them.
1246 // When translating a block that introduces new variables during its scope, we
1247 // need to make sure those variables go out of scope when the block ends. We
1248 // do that by running a 'cleanup' function for each variable.
1249 // trans_block_cleanups runs all the cleanup functions for the block.
1250 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1251 trans_block_cleanups_(bcx, cleanups, false)
1254 pub fn trans_block_cleanups_(bcx: @mut Block,
1255 cleanups: &[cleanup],
1256 /* cleanup_cx: block, */
1257 is_lpad: bool) -> @mut Block {
1258 let _icx = push_ctxt("trans_block_cleanups");
1259 // NB: Don't short-circuit even if this block is unreachable because
1260 // GC-based cleanup needs to the see that the roots are live.
1262 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1263 if bcx.unreachable && !no_lpads { return bcx; }
1265 for cleanups.rev_iter().advance |cu| {
1267 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1268 // Some types don't need to be cleaned up during
1269 // landing pads because they can be freed en mass later
1270 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1279 // In the last argument, Some(block) mean jump to this block, and none means
1280 // this is a landing pad and leaving should be accomplished with a resume
1282 pub fn cleanup_and_leave(bcx: @mut Block,
1283 upto: Option<BasicBlockRef>,
1284 leave: Option<BasicBlockRef>) {
1285 let _icx = push_ctxt("cleanup_and_leave");
1288 let is_lpad = leave == None;
1290 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1292 if bcx.sess().trace() {
1295 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1298 let mut cur_scope = cur.scope;
1300 cur_scope = match cur_scope {
1301 Some (inf) if !inf.empty_cleanups() => {
1302 let (sub_cx, dest, inf_cleanups) = {
1303 let inf = &mut *inf;
1305 let mut dest = None;
1307 let r = (*inf).cleanup_paths.rev_iter().find_(|cp| cp.target == leave);
1308 for r.iter().advance |cp| {
1309 if cp.size == inf.cleanups.len() {
1315 dest = Some(cp.dest);
1318 let sub_cx = sub_block(bcx, "cleanup");
1319 Br(bcx, sub_cx.llbb);
1320 inf.cleanup_paths.push(cleanup_path {
1322 size: inf.cleanups.len(),
1325 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1327 bcx = trans_block_cleanups_(sub_cx,
1330 for dest.iter().advance |&dest| {
1336 Some(inf) => inf.parent,
1342 Some(bb) => { if cur.llbb == bb { break; } }
1345 cur = match cur.parent {
1347 None => { assert!(upto.is_none()); break; }
1351 Some(target) => Br(bcx, target),
1352 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.get())); }
1356 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1357 let _icx = push_ctxt("cleanup_block");
1361 debug!("cleanup_block: %s", cur.to_str());
1363 if bcx.sess().trace() {
1366 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1369 let mut cur_scope = cur.scope;
1371 cur_scope = match cur_scope {
1373 bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1381 Some(bb) => { if cur.llbb == bb { break; } }
1384 cur = match cur.parent {
1386 None => { assert!(upto.is_none()); break; }
1392 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1393 let _icx = push_ctxt("cleanup_and_Br");
1394 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1397 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1398 let _icx = push_ctxt("leave_block");
1399 let next_cx = sub_block(block_parent(out_of), "next");
1400 if bcx.unreachable { Unreachable(next_cx); }
1401 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1405 pub fn with_scope(bcx: @mut Block,
1406 opt_node_info: Option<NodeInfo>,
1408 f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1409 let _icx = push_ctxt("with_scope");
1411 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1412 bcx.to_str(), opt_node_info, name);
1413 let _indenter = indenter();
1415 let scope = simple_block_scope(bcx.scope, opt_node_info);
1416 bcx.scope = Some(scope);
1418 let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1419 bcx.scope = scope.parent;
1423 pub fn with_scope_result(bcx: @mut Block,
1424 opt_node_info: Option<NodeInfo>,
1426 f: &fn(@mut Block) -> Result) -> Result {
1427 let _icx = push_ctxt("with_scope_result");
1429 let scope = simple_block_scope(bcx.scope, opt_node_info);
1430 bcx.scope = Some(scope);
1431 let Result { bcx: out_bcx, val } = f(bcx);
1432 let out_bcx = trans_block_cleanups_(out_bcx,
1433 (scope.cleanups).clone(),
1435 bcx.scope = scope.parent;
1440 pub fn with_scope_datumblock(bcx: @mut Block, opt_node_info: Option<NodeInfo>,
1441 name: &str, f: &fn(@mut Block) -> datum::DatumBlock)
1442 -> datum::DatumBlock {
1443 use middle::trans::datum::DatumBlock;
1445 let _icx = push_ctxt("with_scope_result");
1446 let scope_cx = scope_block(bcx, opt_node_info, name);
1447 Br(bcx, scope_cx.llbb);
1448 let DatumBlock {bcx, datum} = f(scope_cx);
1449 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1452 pub fn block_locals(b: &ast::Block, it: &fn(@ast::Local)) {
1453 for b.stmts.iter().advance |s| {
1455 ast::stmt_decl(d, _) => {
1457 ast::decl_local(ref local) => it(*local),
1458 _ => {} /* fall through */
1461 _ => {} /* fall through */
1466 pub fn with_cond(bcx: @mut Block, val: ValueRef, f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1467 let _icx = push_ctxt("with_cond");
1468 let next_cx = base::sub_block(bcx, "next");
1469 let cond_cx = base::sub_block(bcx, "cond");
1470 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1471 let after_cx = f(cond_cx);
1472 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1476 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1477 let _icx = push_ctxt("call_memcpy");
1479 let key = match ccx.sess.targ_cfg.arch {
1480 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1481 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1483 let memcpy = ccx.intrinsics.get_copy(&key);
1484 let src_ptr = PointerCast(cx, src, Type::i8p());
1485 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1486 let size = IntCast(cx, n_bytes, ccx.int_type);
1487 let align = C_i32(align as i32);
1488 let volatile = C_i1(false);
1489 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1492 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1493 let _icx = push_ctxt("memcpy_ty");
1494 let ccx = bcx.ccx();
1495 if ty::type_is_structural(t) {
1496 let llty = type_of::type_of(ccx, t);
1497 let llsz = llsize_of(ccx, llty);
1498 let llalign = llalign_of_min(ccx, llty);
1499 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1501 Store(bcx, Load(bcx, src), dst);
1505 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1506 if cx.unreachable { return; }
1507 let _icx = push_ctxt("zero_mem");
1510 let llty = type_of::type_of(ccx, t);
1511 memzero(&B(bcx), llptr, llty);
1514 // Always use this function instead of storing a zero constant to the memory
1515 // in question. If you store a zero constant, LLVM will drown in vreg
1516 // allocation for large data structures, and the generated code will be
1517 // awful. (A telltale sign of this is large quantities of
1518 // `mov [byte ptr foo],0` in the generated code.)
1519 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1520 let _icx = push_ctxt("memzero");
1523 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1524 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1525 X86_64 => "llvm.memset.p0i8.i64"
1528 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1529 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1530 let llzeroval = C_u8(0);
1531 let size = machine::llsize_of(ccx, ty);
1532 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1533 let volatile = C_i1(false);
1534 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1537 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1538 let _icx = push_ctxt("alloc_ty");
1539 let ccx = bcx.ccx();
1540 let ty = type_of::type_of(ccx, t);
1541 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1542 let val = alloca(bcx, ty, name);
1546 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1547 alloca_maybe_zeroed(cx, ty, name, false)
1550 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1551 let _icx = push_ctxt("alloca");
1554 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1557 let p = Alloca(cx, ty, name);
1559 let b = cx.fcx.ccx.builder();
1560 b.position_before(cx.fcx.alloca_insert_pt.get());
1566 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1567 let _icx = push_ctxt("arrayalloca");
1570 return llvm::LLVMGetUndef(ty.to_ref());
1573 return ArrayAlloca(cx, ty, v);
1576 pub struct BasicBlocks {
1580 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1582 let cx = task_llcx();
1583 str::as_c_str("static_allocas",
1584 |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf))
1588 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1590 let cx = task_llcx();
1591 str::as_c_str("return",
1592 |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf))
1596 // Creates and returns space for, or returns the argument representing, the
1597 // slot where the return value of the function must go.
1598 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1600 if !ty::type_is_immediate(fcx.ccx.tcx, output_type) {
1601 llvm::LLVMGetParam(fcx.llfn, 0)
1603 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1604 let bcx = fcx.entry_bcx.get();
1605 Alloca(bcx, lloutputtype, "__make_return_pointer")
1610 // NB: must keep 4 fns in sync:
1613 // - create_llargs_for_fn_args.
1616 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1622 param_substs: Option<@param_substs>,
1623 opt_node_info: Option<NodeInfo>,
1625 -> @mut FunctionContext {
1626 for param_substs.iter().advance |p| { p.validate(); }
1628 debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1630 path_str(ccx.sess, path),
1632 param_substs.repr(ccx.tcx));
1634 let substd_output_type = match param_substs {
1635 None => output_type,
1637 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1640 let is_immediate = ty::type_is_immediate(ccx.tcx, substd_output_type);
1641 let fcx = @mut FunctionContext {
1644 llvm::LLVMGetUndef(Type::i8p().to_ref())
1648 alloca_insert_pt: None,
1653 has_immediate_return_value: is_immediate,
1654 llargs: @mut HashMap::new(),
1655 lllocals: @mut HashMap::new(),
1656 llupvars: @mut HashMap::new(),
1658 param_substs: param_substs,
1663 fcx.llenv = unsafe {
1664 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1668 let entry_bcx = top_scope_block(fcx, opt_node_info);
1669 Load(entry_bcx, C_null(Type::i8p()));
1671 fcx.entry_bcx = Some(entry_bcx);
1672 fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1675 if !ty::type_is_nil(substd_output_type) && !(is_immediate && skip_retptr) {
1676 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1681 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1686 -> @mut FunctionContext {
1687 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1690 // NB: must keep 4 fns in sync:
1693 // - create_llargs_for_fn_args.
1697 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1698 // allocas created for them.
1700 // When we translate a function, we need to map its incoming arguments to the
1701 // spaces that have been created for them (by code in the llallocas field of
1702 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1703 // field of the fn_ctxt with
1704 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1708 let _icx = push_ctxt("create_llargs_for_fn_args");
1711 impl_self(tt, self_mode) => {
1712 cx.llself = Some(ValSelfData {
1715 is_copy: self_mode == ty::ByCopy
1721 // Return an array containing the ValueRefs that we get from
1722 // llvm::LLVMGetParam for each argument.
1723 vec::from_fn(args.len(), |i| {
1725 let arg_n = cx.arg_pos(i);
1727 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1729 // FIXME #7260: aliasing should be determined by monomorphized ty::t
1731 // `~` pointers never alias other parameters, because ownership was transferred
1732 ast::ty_uniq(_) => {
1733 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1735 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1736 // those in the other parameters and then mark it as `noalias` if there aren't any
1745 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1748 raw_llargs: &[ValueRef],
1749 arg_tys: &[ty::t]) -> @mut Block {
1750 let _icx = push_ctxt("copy_args_to_allocas");
1755 let self_val = if slf.is_copy
1756 && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1757 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1758 let alloc = alloc_ty(bcx, slf.t, "__self");
1759 Store(bcx, tmp, alloc);
1762 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1765 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1766 add_clean(bcx, self_val, slf.t);
1771 for uint::range(0, arg_tys.len()) |arg_n| {
1772 let arg_ty = arg_tys[arg_n];
1773 let raw_llarg = raw_llargs[arg_n];
1775 // For certain mode/type combinations, the raw llarg values are passed
1776 // by value. However, within the fn body itself, we want to always
1777 // have all locals and arguments be by-ref so that we can cancel the
1778 // cleanup and for better interaction with LLVM's debug info. So, if
1779 // the argument would be passed by value, we store it into an alloca.
1780 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1781 // the event it's not truly needed.
1782 // only by value if immediate:
1783 let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1784 let alloc = alloc_ty(bcx, arg_ty, "__arg");
1785 Store(bcx, raw_llarg, alloc);
1790 bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1792 if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1793 debuginfo::create_argument_metadata(bcx, &args[arg_n], args[arg_n].ty.span);
1800 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1801 // and builds the return block.
1802 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1803 let _icx = push_ctxt("finish_fn");
1805 let ret_cx = match fcx.llreturn {
1807 if !last_bcx.terminated {
1808 Br(last_bcx, llreturn);
1810 raw_block(fcx, false, llreturn)
1814 build_return_block(fcx, ret_cx);
1818 // Builds the return block for a function.
1819 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1820 // Return the value if this function immediate; otherwise, return void.
1821 if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
1822 Ret(ret_cx, Load(ret_cx, fcx.llretptr.get()))
1828 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1830 // trans_closure: Builds an LLVM function out of a source function.
1831 // If the function closes over its environment a closure will be
1833 pub fn trans_closure(ccx: @mut CrateContext,
1835 decl: &ast::fn_decl,
1839 param_substs: Option<@param_substs>,
1841 attributes: &[ast::Attribute],
1843 maybe_load_env: &fn(@mut FunctionContext),
1844 finish: &fn(@mut Block)) {
1845 ccx.stats.n_closures += 1;
1846 let _icx = push_ctxt("trans_closure");
1847 set_uwtable(llfndecl);
1849 debug!("trans_closure(..., param_substs=%s)",
1850 param_substs.repr(ccx.tcx));
1852 // Set up arguments to the function.
1853 let fcx = new_fn_ctxt_w_id(ccx,
1862 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1864 // Set the fixed stack segment flag if necessary.
1865 if attr::contains_name(attributes, "fixed_stack_segment") {
1866 set_no_inline(fcx.llfn);
1867 set_fixed_stack_segment(fcx.llfn);
1870 // Create the first basic block in the function and keep a handle on it to
1871 // pass to finish_fn later.
1872 let bcx_top = fcx.entry_bcx.get();
1873 let mut bcx = bcx_top;
1874 let block_ty = node_id_type(bcx, body.id);
1876 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1877 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1879 maybe_load_env(fcx);
1881 // This call to trans_block is the place where we bridge between
1882 // translation calls that don't have a return value (trans_crate,
1883 // trans_mod, trans_item, et cetera) and those that do
1884 // (trans_block, trans_expr, et cetera).
1885 if body.expr.is_none() || ty::type_is_bot(block_ty) ||
1886 ty::type_is_nil(block_ty)
1888 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1890 let dest = expr::SaveIn(fcx.llretptr.get());
1891 bcx = controlflow::trans_block(bcx, body, dest);
1895 match fcx.llreturn {
1896 Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1897 None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1900 // Put return block after all other blocks.
1901 // This somewhat improves single-stepping experience in debugger.
1903 for fcx.llreturn.iter().advance |&llreturn| {
1904 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1908 // Insert the mandatory first few basic blocks before lltop.
1909 finish_fn(fcx, bcx);
1912 // trans_fn: creates an LLVM function corresponding to a source language
1914 pub fn trans_fn(ccx: @mut CrateContext,
1916 decl: &ast::fn_decl,
1920 param_substs: Option<@param_substs>,
1922 attrs: &[ast::Attribute]) {
1924 let the_path_str = path_str(ccx.sess, path);
1925 let _s = StatRecorder::new(ccx, the_path_str);
1926 debug!("trans_fn(self_arg=%?, param_substs=%s)",
1928 param_substs.repr(ccx.tcx));
1929 let _icx = push_ctxt("trans_fn");
1930 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1942 if ccx.sess.opts.extra_debuginfo
1943 && fcx_has_nonzero_span(fcx) {
1944 debuginfo::create_function_metadata(fcx);
1950 fn insert_synthetic_type_entries(bcx: @mut Block,
1951 fn_args: &[ast::arg],
1955 * For tuple-like structs and enum-variants, we generate
1956 * synthetic AST nodes for the arguments. These have no types
1957 * in the type table and no entries in the moves table,
1958 * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
1959 * gets upset. This hack of a function bridges the gap by inserting types.
1961 * This feels horrible. I think we should just have a special path
1962 * for these functions and not try to use the generic code, but
1963 * that's not the problem I'm trying to solve right now. - nmatsakis
1966 let tcx = bcx.tcx();
1967 for uint::range(0, fn_args.len()) |i| {
1968 debug!("setting type of argument %u (pat node %d) to %s",
1969 i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
1971 let pat_id = fn_args[i].pat.id;
1972 let arg_ty = arg_tys[i];
1973 tcx.node_types.insert(pat_id as uint, arg_ty);
1977 pub fn trans_enum_variant(ccx: @mut CrateContext,
1978 _enum_id: ast::node_id,
1979 variant: &ast::variant,
1980 args: &[ast::variant_arg],
1982 param_substs: Option<@param_substs>,
1983 llfndecl: ValueRef) {
1984 let _icx = push_ctxt("trans_enum_variant");
1986 trans_enum_variant_or_tuple_like_struct(
1995 pub fn trans_tuple_struct(ccx: @mut CrateContext,
1996 fields: &[@ast::struct_field],
1997 ctor_id: ast::node_id,
1998 param_substs: Option<@param_substs>,
1999 llfndecl: ValueRef) {
2000 let _icx = push_ctxt("trans_tuple_struct");
2002 trans_enum_variant_or_tuple_like_struct(
2012 fn id(&self) -> ast::node_id;
2013 fn ty<'a>(&'a self) -> &'a ast::Ty;
2016 impl IdAndTy for ast::variant_arg {
2017 fn id(&self) -> ast::node_id { self.id }
2018 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
2021 impl IdAndTy for @ast::struct_field {
2022 fn id(&self) -> ast::node_id { self.node.id }
2023 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
2026 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2027 ccx: @mut CrateContext,
2028 ctor_id: ast::node_id,
2031 param_substs: Option<@param_substs>,
2034 // Translate variant arguments to function arguments.
2035 let fn_args = do args.map |varg| {
2038 ty: (*varg.ty()).clone(),
2039 pat: ast_util::ident_to_pat(
2040 ccx.tcx.sess.next_node_id(),
2041 codemap::dummy_sp(),
2042 special_idents::arg),
2047 let no_substs: &[ty::t] = [];
2048 let ty_param_substs = match param_substs {
2049 Some(ref substs) => {
2050 let v: &[ty::t] = substs.tys;
2054 let v: &[ty::t] = no_substs;
2059 let ctor_ty = ty::subst_tps(ccx.tcx,
2062 ty::node_id_to_type(ccx.tcx, ctor_id));
2064 let result_ty = match ty::get(ctor_ty).sty {
2065 ty::ty_bare_fn(ref bft) => bft.sig.output,
2067 fmt!("trans_enum_variant_or_tuple_like_struct: \
2068 unexpected ctor return type %s",
2069 ty_to_str(ccx.tcx, ctor_ty)))
2072 let fcx = new_fn_ctxt_w_id(ccx,
2082 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2084 let bcx = fcx.entry_bcx.get();
2085 let arg_tys = ty::ty_fn_args(ctor_ty);
2087 insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2088 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2090 let repr = adt::represent_type(ccx, result_ty);
2091 adt::trans_start_init(bcx, repr, fcx.llretptr.get(), disr);
2092 for fn_args.iter().enumerate().advance |(i, fn_arg)| {
2093 let lldestptr = adt::trans_field_ptr(bcx,
2098 let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2099 let arg_ty = arg_tys[i];
2100 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2102 finish_fn(fcx, bcx);
2105 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2106 id: ast::node_id, vi: @~[@ty::VariantInfo],
2108 for enum_definition.variants.iter().advance |variant| {
2109 let disr_val = vi[*i].disr_val;
2112 match variant.node.kind {
2113 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2114 let llfn = get_item_val(ccx, variant.node.id);
2115 trans_enum_variant(ccx, id, variant, *args,
2116 disr_val, None, llfn);
2118 ast::tuple_variant_kind(_) => {
2121 ast::struct_variant_kind(struct_def) => {
2122 trans_struct_def(ccx, struct_def);
2128 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2129 let _icx = push_ctxt("trans_item");
2130 let path = match ccx.tcx.items.get_copy(&item.id) {
2131 ast_map::node_item(_, p) => p,
2133 _ => fail!("trans_item"),
2136 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2137 if purity == ast::extern_fn {
2138 let llfndecl = get_item_val(ccx, item.id);
2139 foreign::trans_foreign_fn(ccx,
2140 vec::append((*path).clone(),
2141 [path_name(item.ident)]),
2146 } else if !generics.is_type_parameterized() {
2147 let llfndecl = get_item_val(ccx, item.id);
2149 vec::append((*path).clone(), [path_name(item.ident)]),
2158 for body.stmts.iter().advance |stmt| {
2160 ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2169 ast::item_impl(ref generics, _, _, ref ms) => {
2170 meth::trans_impl(ccx,
2177 ast::item_mod(ref m) => {
2180 ast::item_enum(ref enum_definition, ref generics) => {
2181 if !generics.is_type_parameterized() {
2182 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2184 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2187 ast::item_static(_, m, expr) => {
2188 consts::trans_const(ccx, m, item.id);
2189 // Do static_assert checking. It can't really be done much earlier because we need to get
2190 // the value of the bool out of LLVM
2191 for item.attrs.iter().advance |attr| {
2192 if "static_assert" == attr.name() {
2193 if m == ast::m_mutbl {
2194 ccx.sess.span_fatal(expr.span,
2195 "cannot have static_assert on a mutable static");
2197 let v = ccx.const_values.get_copy(&item.id);
2199 if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2200 ccx.sess.span_fatal(expr.span, "static assertion failed");
2206 ast::item_foreign_mod(ref foreign_mod) => {
2207 foreign::trans_foreign_mod(ccx, path, foreign_mod);
2209 ast::item_struct(struct_def, ref generics) => {
2210 if !generics.is_type_parameterized() {
2211 trans_struct_def(ccx, struct_def);
2214 _ => {/* fall through */ }
2218 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2219 // If this is a tuple-like struct, translate the constructor.
2220 match struct_def.ctor_id {
2221 // We only need to translate a constructor if there are fields;
2222 // otherwise this is a unit-like struct.
2223 Some(ctor_id) if struct_def.fields.len() > 0 => {
2224 let llfndecl = get_item_val(ccx, ctor_id);
2225 trans_tuple_struct(ccx, struct_def.fields,
2226 ctor_id, None, llfndecl);
2228 Some(_) | None => {}
2232 // Translate a module. Doing this amounts to translating the items in the
2233 // module; there ends up being no artifact (aside from linkage names) of
2234 // separate modules in the compiled program. That's because modules exist
2235 // only as a convenience for humans working with the code, to organize names
2236 // and control visibility.
2237 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2238 let _icx = push_ctxt("trans_mod");
2239 for m.items.iter().advance |item| {
2240 trans_item(ccx, *item);
2244 pub fn register_fn(ccx: @mut CrateContext,
2247 node_id: ast::node_id,
2248 attrs: &[ast::Attribute])
2250 let t = ty::node_id_to_type(ccx.tcx, node_id);
2251 register_fn_full(ccx, sp, path, node_id, attrs, t)
2254 pub fn register_fn_full(ccx: @mut CrateContext,
2257 node_id: ast::node_id,
2258 attrs: &[ast::Attribute],
2261 let llfty = type_of_fn_from_ty(ccx, node_type);
2262 register_fn_fuller(ccx, sp, path, node_id, attrs, node_type,
2263 lib::llvm::CCallConv, llfty)
2266 pub fn register_fn_fuller(ccx: @mut CrateContext,
2269 node_id: ast::node_id,
2270 attrs: &[ast::Attribute],
2272 cc: lib::llvm::CallConv,
2275 debug!("register_fn_fuller creating fn for item %d with path %s",
2277 ast_map::path_to_str(path, token::get_ident_interner()));
2279 let ps = if attr::contains_name(attrs, "no_mangle") {
2280 path_elt_to_str(*path.last(), token::get_ident_interner())
2282 mangle_exported_name(ccx, path, node_type)
2285 let llfn = decl_fn(ccx.llmod, ps, cc, fn_ty);
2286 ccx.item_symbols.insert(node_id, ps);
2288 // FIXME #4404 android JNI hacks
2289 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2290 (*ccx.sess.building_library &&
2291 ccx.sess.targ_cfg.os == session::os_android));
2293 create_entry_wrapper(ccx, sp, llfn);
2298 pub fn is_entry_fn(sess: &Session, node_id: ast::node_id) -> bool {
2299 match *sess.entry_fn {
2300 Some((entry_id, _)) => node_id == entry_id,
2305 // Create a _rust_main(args: ~[str]) function which will be called from the
2306 // runtime rust_start function
2307 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2308 _sp: span, main_llfn: ValueRef) {
2309 let et = ccx.sess.entry_type.unwrap();
2310 if et == session::EntryMain {
2311 let llfn = create_main(ccx, main_llfn);
2312 create_entry_fn(ccx, llfn, true);
2314 create_entry_fn(ccx, main_llfn, false);
2317 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2318 let nt = ty::mk_nil();
2320 let llfty = type_of_fn(ccx, [], nt);
2321 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2322 lib::llvm::CCallConv, llfty);
2324 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2326 // the args vector built in create_entry_fn will need
2327 // be updated if this assertion starts to fail.
2328 assert!(fcx.has_immediate_return_value);
2330 let bcx = fcx.entry_bcx.get();
2332 let llenvarg = unsafe {
2333 let env_arg = fcx.env_arg_pos();
2334 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2336 let args = ~[llenvarg];
2337 Call(bcx, main_llfn, args);
2339 finish_fn(fcx, bcx);
2343 fn create_entry_fn(ccx: @mut CrateContext,
2344 rust_main: ValueRef,
2345 use_start_lang_item: bool) {
2346 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2349 // FIXME #4404 android JNI hacks
2350 let llfn = if *ccx.sess.building_library {
2351 decl_cdecl_fn(ccx.llmod, "amain", llfty)
2353 let main_name = match ccx.sess.targ_cfg.os {
2354 session::os_win32 => ~"WinMain@16",
2357 decl_cdecl_fn(ccx.llmod, main_name, llfty)
2359 let llbb = str::as_c_str("top", |buf| {
2361 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2364 let bld = ccx.builder.B;
2366 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2368 let crate_map = ccx.crate_map;
2369 let opaque_crate_map = do "crate_map".as_c_str |buf| {
2370 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2373 let (start_fn, args) = if use_start_lang_item {
2374 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2376 Err(s) => { ccx.tcx.sess.fatal(s); }
2378 let start_fn = if start_def_id.crate == ast::local_crate {
2379 get_item_val(ccx, start_def_id.node)
2381 let start_fn_type = csearch::get_type(ccx.tcx,
2383 trans_external_path(ccx, start_def_id, start_fn_type)
2387 let opaque_rust_main = do "rust_main".as_c_str |buf| {
2388 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2392 C_null(Type::opaque_box(ccx).ptr_to()),
2394 llvm::LLVMGetParam(llfn, 0),
2395 llvm::LLVMGetParam(llfn, 1),
2401 debug!("using user-defined start fn");
2403 C_null(Type::opaque_box(ccx).ptr_to()),
2404 llvm::LLVMGetParam(llfn, 0 as c_uint),
2405 llvm::LLVMGetParam(llfn, 1 as c_uint),
2412 let result = llvm::LLVMBuildCall(bld,
2415 args.len() as c_uint,
2417 llvm::LLVMBuildRet(bld, result);
2422 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2423 llenvptr: ValueRef) {
2424 let ccx = bcx.ccx();
2425 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2426 Store(bcx, llfn, code_cell);
2427 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2428 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2429 Store(bcx, llenvblobptr, env_cell);
2432 pub fn item_path(ccx: &CrateContext, i: &ast::item) -> path {
2433 let base = match ccx.tcx.items.get_copy(&i.id) {
2434 ast_map::node_item(_, p) => p,
2435 // separate map for paths?
2436 _ => fail!("item_path")
2438 vec::append((*base).clone(), [path_name(i.ident)])
2441 pub fn get_item_val(ccx: @mut CrateContext, id: ast::node_id) -> ValueRef {
2442 debug!("get_item_val(id=`%?`)", id);
2443 let val = ccx.item_vals.find_copy(&id);
2447 let mut exprt = false;
2448 let item = ccx.tcx.items.get_copy(&id);
2449 let val = match item {
2450 ast_map::node_item(i, pth) => {
2451 let my_path = vec::append((*pth).clone(), [path_name(i.ident)]);
2452 let v = match i.node {
2453 ast::item_static(_, m, expr) => {
2454 let typ = ty::node_id_to_type(ccx.tcx, i.id);
2455 let s = mangle_exported_name(ccx, my_path, typ);
2456 // We need the translated value here, because for enums the
2457 // LLVM type is not fully determined by the Rust type.
2458 let v = consts::const_expr(ccx, expr);
2459 ccx.const_values.insert(id, v);
2460 exprt = m == ast::m_mutbl;
2462 let llty = llvm::LLVMTypeOf(v);
2463 let g = str::as_c_str(s, |buf| {
2464 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2466 ccx.item_symbols.insert(i.id, s);
2470 ast::item_fn(_, purity, _, _, _) => {
2471 let llfn = if purity != ast::extern_fn {
2472 register_fn(ccx, i.span, my_path, i.id, i.attrs)
2474 foreign::register_foreign_fn(ccx,
2480 set_inline_hint_if_appr(i.attrs, llfn);
2483 _ => fail!("get_item_val: weird result in table")
2485 match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2486 Some(sect) => unsafe {
2487 do sect.as_c_str |buf| {
2488 llvm::LLVMSetSection(v, buf);
2495 ast_map::node_trait_method(trait_method, _, pth) => {
2496 debug!("get_item_val(): processing a node_trait_method");
2497 match *trait_method {
2498 ast::required(_) => {
2499 ccx.sess.bug("unexpected variant: required trait method in \
2502 ast::provided(m) => {
2504 register_method(ccx, id, pth, m)
2508 ast_map::node_method(m, _, pth) => {
2509 register_method(ccx, id, pth, m)
2511 ast_map::node_foreign_item(ni, _, _, pth) => {
2514 ast::foreign_item_fn(*) => {
2515 register_fn(ccx, ni.span,
2516 vec::append((*pth).clone(),
2517 [path_name(ni.ident)]),
2521 ast::foreign_item_static(*) => {
2522 let typ = ty::node_id_to_type(ccx.tcx, ni.id);
2523 let ident = token::ident_to_str(&ni.ident);
2524 let g = do str::as_c_str(ident) |buf| {
2526 let ty = type_of(ccx, typ);
2527 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2535 ast_map::node_variant(ref v, enm, pth) => {
2538 ast::tuple_variant_kind(ref args) => {
2539 assert!(args.len() != 0u);
2540 let pth = vec::append((*pth).clone(),
2541 [path_name(enm.ident),
2542 path_name((*v).node.name)]);
2543 llfn = match enm.node {
2544 ast::item_enum(_, _) => {
2545 register_fn(ccx, (*v).span, pth, id, enm.attrs)
2547 _ => fail!("node_variant, shouldn't happen")
2550 ast::struct_variant_kind(_) => {
2551 fail!("struct variant kind unexpected in get_item_val")
2554 set_inline_hint(llfn);
2558 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2559 // Only register the constructor if this is a tuple-like struct.
2560 match struct_def.ctor_id {
2562 ccx.tcx.sess.bug("attempt to register a constructor of \
2563 a non-tuple-like struct")
2566 let llfn = register_fn(ccx,
2568 (*struct_path).clone(),
2571 set_inline_hint(llfn);
2578 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2582 if !exprt && !ccx.reachable.contains(&id) {
2583 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2585 ccx.item_vals.insert(id, val);
2591 pub fn register_method(ccx: @mut CrateContext,
2593 path: @ast_map::path,
2594 m: @ast::method) -> ValueRef {
2595 let mty = ty::node_id_to_type(ccx.tcx, id);
2597 let mut path = (*path).clone();
2598 path.push(path_name(gensym_name("meth")));
2599 path.push(path_name(m.ident));
2601 let llfn = register_fn_full(ccx, m.span, path, id, m.attrs, mty);
2602 set_inline_hint_if_appr(m.attrs, llfn);
2606 // The constant translation pass.
2607 pub fn trans_constant(ccx: &mut CrateContext, it: @ast::item) {
2608 let _icx = push_ctxt("trans_constant");
2610 ast::item_enum(ref enum_definition, _) => {
2611 let vi = ty::enum_variants(ccx.tcx,
2612 ast::def_id { crate: ast::local_crate,
2615 let path = item_path(ccx, it);
2616 for (*enum_definition).variants.iter().advance |variant| {
2617 let p = vec::append(path.clone(), [
2618 path_name(variant.node.name),
2619 path_name(special_idents::descrim)
2621 let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2622 let disr_val = vi[i].disr_val;
2623 note_unique_llvm_symbol(ccx, s);
2624 let discrim_gvar = str::as_c_str(s, |buf| {
2626 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2630 llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, disr_val));
2631 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2633 ccx.discrims.insert(
2634 local_def(variant.node.id), discrim_gvar);
2635 ccx.discrim_symbols.insert(variant.node.id, s);
2643 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::Crate) {
2646 visit::mk_simple_visitor(@visit::SimpleVisitor {
2647 visit_item: |a| trans_constant(ccx, a),
2648 ..*visit::default_simple_visitor()
2652 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2654 return PtrToInt(cx, v, ccx.int_type);
2657 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2659 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2664 ($name:expr, $args:expr, $ret:expr) => ({
2666 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2667 intrinsics.insert(name, f);
2671 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2672 let i8p = Type::i8p();
2673 let mut intrinsics = HashMap::new();
2675 ifn!("llvm.memcpy.p0i8.p0i8.i32",
2676 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2677 ifn!("llvm.memcpy.p0i8.p0i8.i64",
2678 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2679 ifn!("llvm.memmove.p0i8.p0i8.i32",
2680 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2681 ifn!("llvm.memmove.p0i8.p0i8.i64",
2682 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2683 ifn!("llvm.memset.p0i8.i32",
2684 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2685 ifn!("llvm.memset.p0i8.i64",
2686 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2688 ifn!("llvm.trap", [], Type::void());
2689 ifn!("llvm.frameaddress", [Type::i32()], i8p);
2691 ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2692 ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2693 ifn!("llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2694 ifn!("llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2696 ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2697 ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2698 ifn!("llvm.sin.f32", [Type::f32()], Type::f32());
2699 ifn!("llvm.sin.f64", [Type::f64()], Type::f64());
2700 ifn!("llvm.cos.f32", [Type::f32()], Type::f32());
2701 ifn!("llvm.cos.f64", [Type::f64()], Type::f64());
2702 ifn!("llvm.exp.f32", [Type::f32()], Type::f32());
2703 ifn!("llvm.exp.f64", [Type::f64()], Type::f64());
2704 ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2705 ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2706 ifn!("llvm.log.f32", [Type::f32()], Type::f32());
2707 ifn!("llvm.log.f64", [Type::f64()], Type::f64());
2708 ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2709 ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2710 ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2711 ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2713 ifn!("llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2714 ifn!("llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2716 ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2717 ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2718 ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2719 ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2720 ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2721 ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2722 ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2723 ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2725 ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2726 ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2727 ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2728 ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2730 ifn!("llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2731 ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2732 ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2733 ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2735 ifn!("llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2736 ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2737 ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2738 ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2740 ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2741 ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2742 ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2747 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2748 ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2749 ifn!("llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2752 pub fn trap(bcx: @mut Block) {
2753 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2754 Some(&x) => { Call(bcx, x, []); },
2755 _ => bcx.sess().bug("unbound llvm.trap in trap")
2759 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2760 if !ccx.sess.opts.gc || !ccx.uses_gc {
2764 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2765 let gc_metadata = do str::as_c_str(gc_metadata_name) |buf| {
2767 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2771 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2772 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2773 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2777 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2778 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2779 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2780 let map = do "_rust_mod_map".as_c_str |buf| {
2782 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2785 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2786 let mut elts: ~[ValueRef] = ~[];
2788 // This is not ideal, but the borrow checker doesn't
2789 // like the multiple borrows. At least, it doesn't
2790 // like them on the current snapshot. (2013-06-14)
2792 for ccx.module_data.each_key |k| {
2793 keys.push(k.to_managed());
2796 for keys.iter().advance |key| {
2797 let val = *ccx.module_data.find_equiv(key).get();
2798 let s_const = C_cstr(ccx, *key);
2799 let s_ptr = p2i(ccx, s_const);
2800 let v_ptr = p2i(ccx, val);
2801 let elt = C_struct([s_ptr, v_ptr]);
2804 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2807 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2813 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2814 llmod: ModuleRef) -> ValueRef {
2815 let targ_cfg = sess.targ_cfg;
2816 let int_type = Type::int(targ_cfg.arch);
2817 let mut n_subcrates = 1;
2818 let cstore = sess.cstore;
2819 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2820 let mapname = if *sess.building_library {
2821 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2825 let sym_name = ~"_rust_crate_map_" + mapname;
2826 let arrtype = Type::array(&int_type, n_subcrates as u64);
2827 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2828 let map = str::as_c_str(sym_name, |buf| {
2830 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2833 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2837 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2838 let mut subcrates: ~[ValueRef] = ~[];
2840 let cstore = ccx.sess.cstore;
2841 while cstore::have_crate_data(cstore, i) {
2842 let cdata = cstore::get_crate_data(cstore, i);
2843 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2845 cstore::get_crate_vers(cstore, i),
2846 cstore::get_crate_hash(cstore, i));
2847 let cr = str::as_c_str(nm, |buf| {
2849 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2852 subcrates.push(p2i(ccx, cr));
2855 subcrates.push(C_int(ccx, 0));
2857 let llannihilatefn = match ccx.tcx.lang_items.annihilate_fn() {
2858 Some(annihilate_def_id) => {
2859 if annihilate_def_id.crate == ast::local_crate {
2860 get_item_val(ccx, annihilate_def_id.node)
2862 let annihilate_fn_type = csearch::get_type(ccx.tcx,
2863 annihilate_def_id).ty;
2864 trans_external_path(ccx, annihilate_def_id, annihilate_fn_type)
2867 None => { C_null(Type::i8p()) }
2871 let mod_map = create_module_map(ccx);
2872 llvm::LLVMSetInitializer(map, C_struct(
2874 lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2876 C_array(ccx.int_type, subcrates)]));
2880 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2881 -> encoder::EncodeParams<'r> {
2883 let diag = cx.sess.diagnostic();
2884 let item_symbols = &cx.item_symbols;
2885 let discrim_symbols = &cx.discrim_symbols;
2886 let link_meta = &cx.link_meta;
2887 encoder::EncodeParams {
2890 reexports2: cx.exp_map2,
2891 item_symbols: item_symbols,
2892 discrim_symbols: discrim_symbols,
2893 link_meta: link_meta,
2894 cstore: cx.sess.cstore,
2895 encode_inlined_item: ie,
2896 reachable: cx.reachable,
2900 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) {
2901 if !*cx.sess.building_library { return; }
2903 let encode_inlined_item: encoder::encode_inlined_item =
2904 |ecx, ebml_w, path, ii|
2905 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2907 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2908 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2909 let llconst = C_struct([llmeta]);
2910 let mut llglobal = str::as_c_str("rust_metadata", |buf| {
2912 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2916 llvm::LLVMSetInitializer(llglobal, llconst);
2917 str::as_c_str(cx.sess.targ_cfg.target_strs.meta_sect_name, |buf| {
2918 llvm::LLVMSetSection(llglobal, buf)
2920 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2922 let t_ptr_i8 = Type::i8p();
2923 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2924 let llvm_used = do "llvm.used".as_c_str |buf| {
2925 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2927 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2928 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2932 fn mk_global(ccx: &CrateContext,
2938 let llglobal = do str::as_c_str(name) |buf| {
2939 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
2941 llvm::LLVMSetInitializer(llglobal, llval);
2942 llvm::LLVMSetGlobalConstant(llglobal, True);
2945 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2952 // Writes the current ABI version into the crate.
2953 pub fn write_abi_version(ccx: &mut CrateContext) {
2954 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
2957 pub fn trans_crate(sess: session::Session,
2961 emap2: resolve::ExportMap2,
2962 reachable_map: @mut HashSet<ast::node_id>,
2963 maps: astencode::Maps)
2964 -> (ContextRef, ModuleRef, LinkMeta) {
2965 // Before we touch LLVM, make sure that multithreading is enabled.
2966 if unsafe { !llvm::LLVMRustStartMultithreading() } {
2967 //sess.bug("couldn't enable multi-threaded LLVM");
2970 let mut symbol_hasher = hash::default_state();
2971 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
2973 // Append ".rc" to crate name as LLVM module identifier.
2975 // LLVM code generator emits a ".file filename" directive
2976 // for ELF backends. Value of the "filename" is set as the
2977 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2978 // crashes if the module identifer is same as other symbols
2979 // such as a function name in the module.
2980 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2981 let llmod_id = link_meta.name.to_owned() + ".rc";
2983 let ccx = @mut CrateContext::new(sess,
2993 let _icx = push_ctxt("data");
2994 trans_constants(ccx, crate);
2998 let _icx = push_ctxt("text");
2999 trans_mod(ccx, &crate.module);
3002 decl_gc_metadata(ccx, llmod_id);
3003 fill_crate_map(ccx, ccx.crate_map);
3004 glue::emit_tydescs(ccx);
3005 write_abi_version(ccx);
3006 if ccx.sess.opts.debuginfo {
3007 debuginfo::finalize(ccx);
3010 // Translate the metadata.
3011 write_metadata(ccx, crate);
3012 if ccx.sess.trans_stats() {
3013 io::println("--- trans stats ---");
3014 io::println(fmt!("n_static_tydescs: %u",
3015 ccx.stats.n_static_tydescs));
3016 io::println(fmt!("n_glues_created: %u",
3017 ccx.stats.n_glues_created));
3018 io::println(fmt!("n_null_glues: %u", ccx.stats.n_null_glues));
3019 io::println(fmt!("n_real_glues: %u", ccx.stats.n_real_glues));
3021 io::println(fmt!("n_fns: %u", ccx.stats.n_fns));
3022 io::println(fmt!("n_monos: %u", ccx.stats.n_monos));
3023 io::println(fmt!("n_inlines: %u", ccx.stats.n_inlines));
3024 io::println(fmt!("n_closures: %u", ccx.stats.n_closures));
3025 io::println("fn stats:");
3026 do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3029 for ccx.stats.fn_stats.iter().advance |tuple| {
3031 (ref name, ms, insns) => {
3032 io::println(fmt!("%u insns, %u ms, %s", insns, ms, *name));
3037 if ccx.sess.count_llvm_insns() {
3038 for ccx.stats.llvm_insns.iter().advance |(k, v)| {
3039 io::println(fmt!("%-7u %s", *v, *k));
3043 let llcx = ccx.llcx;
3044 let link_meta = ccx.link_meta;
3045 let llmod = ccx.llmod;
3047 return (llcx, llmod, link_meta);