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.
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
31 use driver::session::Session;
32 use lib::llvm::{ContextRef, ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
39 use middle::trans::_match;
40 use middle::trans::adt;
41 use middle::trans::base;
42 use middle::trans::build::*;
43 use middle::trans::callee;
44 use middle::trans::common::*;
45 use middle::trans::consts;
46 use middle::trans::controlflow;
47 use middle::trans::datum;
48 use middle::trans::debuginfo;
49 use middle::trans::expr;
50 use middle::trans::foreign;
51 use middle::trans::glue;
52 use middle::trans::inline;
53 use middle::trans::machine;
54 use middle::trans::machine::{llalign_of_min, llsize_of};
55 use middle::trans::meth;
56 use middle::trans::monomorphize;
57 use middle::trans::reachable;
58 use middle::trans::shape::*;
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 core::hashmap::{HashMap};
72 use core::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, path_to_ident};
82 use syntax::codemap::span;
83 use syntax::parse::token;
84 use syntax::parse::token::{special_idents};
85 use syntax::print::pprust::stmt_to_str;
87 use syntax::{ast, ast_util, codemap, ast_map};
88 use syntax::abi::{X86, X86_64, Arm, Mips};
90 pub use middle::trans::context::task_llcx;
92 fn task_local_insn_key(_v: @~[&'static str]) {}
94 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
96 let opt = local_data::local_data_get(task_local_insn_key);
103 pub fn init_insn_ctxt() {
105 local_data::local_data_set(task_local_insn_key, @~[]);
109 pub struct _InsnCtxt { _x: () }
112 impl Drop for _InsnCtxt {
115 do local_data::local_data_modify(task_local_insn_key) |c| {
116 do c.map_consume |@ctx| {
126 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
127 debug!("new InsnCtxt: %s", s);
129 do local_data::local_data_modify(task_local_insn_key) |c| {
130 do c.map_consume |@ctx| {
140 fn fcx_has_nonzero_span(fcx: fn_ctxt) -> bool {
143 Some(span) => *span.lo != 0 || *span.hi != 0
147 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
148 let llfn: ValueRef = do name.as_c_str |buf| {
150 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
154 lib::llvm::SetFunctionCallConv(llfn, cc);
158 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
159 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
162 // Only use this if you are going to actually define the function. It's
163 // not valid to simply declare a function as internal.
164 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: ~str, ty: Type) -> ValueRef {
165 let llfn = decl_cdecl_fn(llmod, name, ty);
166 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
170 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
171 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
172 match externs.find_copy(&name) {
176 let f = decl_fn(llmod, name, cc, ty);
177 externs.insert(name, f);
181 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
182 name: @str, ty: Type) -> ValueRef {
183 match externs.find_copy(&name) {
188 let c = do name.as_c_str |buf| {
189 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
191 externs.insert(name, c);
195 pub fn umax(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
196 let _icx = push_ctxt("umax");
197 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
198 return Select(cx, cond, b, a);
201 pub fn umin(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
202 let _icx = push_ctxt("umin");
203 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
204 return Select(cx, cond, a, b);
207 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
208 // The type of the returned pointer is always i8*. If you care about the
209 // return type, use bump_ptr().
210 pub fn ptr_offs(bcx: block, base: ValueRef, sz: ValueRef) -> ValueRef {
211 let _icx = push_ctxt("ptr_offs");
212 let raw = PointerCast(bcx, base, Type::i8p());
213 InBoundsGEP(bcx, raw, [sz])
216 // Increment a pointer by a given amount and then cast it to be a pointer
218 pub fn bump_ptr(bcx: block, t: ty::t, base: ValueRef, sz: ValueRef) ->
220 let _icx = push_ctxt("bump_ptr");
222 let bumped = ptr_offs(bcx, base, sz);
223 let typ = type_of(ccx, t).ptr_to();
224 PointerCast(bcx, bumped, typ)
227 // Returns a pointer to the body for the box. The box may be an opaque
228 // box. The result will be casted to the type of body_t, if it is statically
231 // The runtime equivalent is box_body() in "rust_internal.h".
232 pub fn opaque_box_body(bcx: block,
234 boxptr: ValueRef) -> ValueRef {
235 let _icx = push_ctxt("opaque_box_body");
237 let ty = type_of(ccx, body_t);
238 let ty = Type::box(ccx, &ty);
239 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
240 GEPi(bcx, boxptr, [0u, abi::box_field_body])
243 // malloc_raw_dyn: allocates a box to contain a given type, but with a
244 // potentially dynamic size.
245 pub fn malloc_raw_dyn(bcx: block,
248 size: ValueRef) -> Result {
249 let _icx = push_ctxt("malloc_raw");
252 let (mk_fn, langcall) = match heap {
253 heap_managed | heap_managed_unique => {
254 (ty::mk_imm_box, bcx.tcx().lang_items.malloc_fn())
257 (ty::mk_imm_uniq, bcx.tcx().lang_items.exchange_malloc_fn())
261 // Grab the TypeRef type of box_ptr_ty.
262 let box_ptr_ty = mk_fn(bcx.tcx(), t);
263 let llty = type_of(ccx, box_ptr_ty);
265 // Get the tydesc for the body:
266 let static_ti = get_tydesc(ccx, t);
267 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
270 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
271 let rval = alloca(bcx, Type::i8p());
272 let bcx = callee::trans_lang_call(
277 let r = rslt(bcx, PointerCast(bcx, Load(bcx, rval), llty));
278 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
282 // malloc_raw: expects an unboxed type and returns a pointer to
283 // enough space for a box of that type. This includes a rust_opaque_box
285 pub fn malloc_raw(bcx: block, t: ty::t, heap: heap) -> Result {
286 let ty = type_of(bcx.ccx(), t);
287 let size = llsize_of(bcx.ccx(), ty);
288 malloc_raw_dyn(bcx, t, heap, size)
291 pub struct MallocResult {
297 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
298 // and pulls out the body
299 pub fn malloc_general_dyn(bcx: block, t: ty::t, heap: heap, size: ValueRef)
301 let _icx = push_ctxt("malloc_general");
302 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
303 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
305 MallocResult { bcx: bcx, box: llbox, body: body }
308 pub fn malloc_general(bcx: block, t: ty::t, heap: heap)
310 let ty = type_of(bcx.ccx(), t);
311 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
313 pub fn malloc_boxed(bcx: block, t: ty::t)
315 malloc_general(bcx, t, heap_managed)
318 pub fn heap_for_unique(bcx: block, t: ty::t) -> heap {
319 if ty::type_contents(bcx.tcx(), t).contains_managed() {
326 pub fn maybe_set_managed_unique_rc(bcx: block, bx: ValueRef, heap: heap) {
327 if heap == heap_managed_unique {
328 // In cases where we are looking at a unique-typed allocation in the
329 // managed heap (thus have refcount 1 from the managed allocator),
330 // such as a ~(@foo) or such. These need to have their refcount forced
331 // to -2 so the annihilator ignores them.
332 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
333 let rc_val = C_int(bcx.ccx(), -2);
334 Store(bcx, rc_val, rc);
338 pub fn malloc_unique(bcx: block, t: ty::t)
340 malloc_general(bcx, t, heap_for_unique(bcx, t))
343 // Type descriptor and type glue stuff
345 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
346 get_tydesc(ccx, t).tydesc
349 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
350 match ccx.tydescs.find(&t) {
357 ccx.stats.n_static_tydescs += 1u;
358 let inf = glue::declare_tydesc(ccx, t);
359 ccx.tydescs.insert(t, inf);
363 pub fn set_optimize_for_size(f: ValueRef) {
365 llvm::LLVMAddFunctionAttr(f,
366 lib::llvm::OptimizeForSizeAttribute
372 pub fn set_no_inline(f: ValueRef) {
374 llvm::LLVMAddFunctionAttr(f,
375 lib::llvm::NoInlineAttribute as c_uint,
380 pub fn set_no_unwind(f: ValueRef) {
382 llvm::LLVMAddFunctionAttr(f,
383 lib::llvm::NoUnwindAttribute as c_uint,
388 // Tell LLVM to emit the information necessary to unwind the stack for the
390 pub fn set_uwtable(f: ValueRef) {
392 llvm::LLVMAddFunctionAttr(f,
393 lib::llvm::UWTableAttribute as c_uint,
398 pub fn set_inline_hint(f: ValueRef) {
400 llvm::LLVMAddFunctionAttr(f,
401 lib::llvm::InlineHintAttribute as c_uint,
406 pub fn set_inline_hint_if_appr(attrs: &[ast::attribute],
408 match attr::find_inline_attr(attrs) {
409 attr::ia_hint => set_inline_hint(llfn),
410 attr::ia_always => set_always_inline(llfn),
411 attr::ia_never => set_no_inline(llfn),
412 attr::ia_none => { /* fallthrough */ }
416 pub fn set_always_inline(f: ValueRef) {
418 llvm::LLVMAddFunctionAttr(f,
419 lib::llvm::AlwaysInlineAttribute as c_uint,
424 pub fn set_fixed_stack_segment(f: ValueRef) {
426 llvm::LLVMAddFunctionAttr(f, 0, 1 << (39 - 32));
430 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
431 if ty::type_is_structural(t) {
432 set_optimize_for_size(f);
433 } else { set_always_inline(f); }
436 // Double-check that we never ask LLVM to declare the same symbol twice. It
437 // silently mangles such symbols, breaking our linkage model.
438 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
439 if ccx.all_llvm_symbols.contains(&sym) {
440 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
442 ccx.all_llvm_symbols.insert(sym);
446 pub fn get_res_dtor(ccx: @mut CrateContext,
448 parent_id: ast::def_id,
451 let _icx = push_ctxt("trans_res_dtor");
452 if !substs.is_empty() {
453 let did = if did.crate != ast::local_crate {
454 inline::maybe_instantiate_inline(ccx, did, true)
458 assert_eq!(did.crate, ast::local_crate);
459 let tsubsts = ty::substs { self_r: None, self_ty: None,
460 tps: /*bad*/ substs.to_owned() };
461 let (val, _) = monomorphize::monomorphic_fn(ccx,
469 } else if did.crate == ast::local_crate {
470 get_item_val(ccx, did.node)
473 let name = csearch::get_symbol(ccx.sess.cstore, did);
474 let class_ty = ty::subst_tps(tcx,
477 ty::lookup_item_type(tcx, parent_id).ty);
478 let llty = type_of_dtor(ccx, class_ty);
479 let name = name.to_managed(); // :-(
480 get_extern_fn(&mut ccx.externs,
483 lib::llvm::CCallConv,
488 // Structural comparison: a rather involved form of glue.
489 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
490 if cx.sess.opts.save_temps {
491 let _: () = str::as_c_str(s, |buf| {
493 llvm::LLVMSetValueName(v, buf)
500 // Used only for creating scalar comparison glue.
501 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
503 // NB: This produces an i1, not a Rust bool (i8).
504 pub fn compare_scalar_types(cx: block,
510 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
512 match ty::get(t).sty {
513 ty::ty_nil => rslt(cx, f(nil_type)),
514 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
515 ty::ty_int(_) => rslt(cx, f(signed_int)),
516 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
517 ty::ty_float(_) => rslt(cx, f(floating_point)),
520 controlflow::trans_fail(
522 @"attempt to compare values of type type"),
526 // Should never get here, because t is scalar.
527 cx.sess().bug("non-scalar type passed to \
528 compare_scalar_types")
534 // A helper function to do the actual comparison of scalar values.
535 pub fn compare_scalar_values(cx: block,
541 let _icx = push_ctxt("compare_scalar_values");
542 fn die(cx: block) -> ! {
543 cx.tcx().sess.bug("compare_scalar_values: must be a\
544 comparison operator");
548 // We don't need to do actual comparisons for nil.
549 // () == () holds but () < () does not.
551 ast::eq | ast::le | ast::ge => return C_i1(true),
552 ast::ne | ast::lt | ast::gt => return C_i1(false),
553 // refinements would be nice
559 ast::eq => lib::llvm::RealOEQ,
560 ast::ne => lib::llvm::RealUNE,
561 ast::lt => lib::llvm::RealOLT,
562 ast::le => lib::llvm::RealOLE,
563 ast::gt => lib::llvm::RealOGT,
564 ast::ge => lib::llvm::RealOGE,
567 return FCmp(cx, cmp, lhs, rhs);
571 ast::eq => lib::llvm::IntEQ,
572 ast::ne => lib::llvm::IntNE,
573 ast::lt => lib::llvm::IntSLT,
574 ast::le => lib::llvm::IntSLE,
575 ast::gt => lib::llvm::IntSGT,
576 ast::ge => lib::llvm::IntSGE,
579 return ICmp(cx, cmp, lhs, rhs);
583 ast::eq => lib::llvm::IntEQ,
584 ast::ne => lib::llvm::IntNE,
585 ast::lt => lib::llvm::IntULT,
586 ast::le => lib::llvm::IntULE,
587 ast::gt => lib::llvm::IntUGT,
588 ast::ge => lib::llvm::IntUGE,
591 return ICmp(cx, cmp, lhs, rhs);
596 pub type val_pair_fn = @fn(block, ValueRef, ValueRef) -> block;
597 pub type val_and_ty_fn = @fn(block, ValueRef, ty::t) -> block;
599 pub fn load_inbounds(cx: block, p: ValueRef, idxs: &[uint]) -> ValueRef {
600 return Load(cx, GEPi(cx, p, idxs));
603 pub fn store_inbounds(cx: block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
604 Store(cx, v, GEPi(cx, p, idxs));
607 // Iterates through the elements of a structural type.
608 pub fn iter_structural_ty(cx: block, av: ValueRef, t: ty::t,
609 f: val_and_ty_fn) -> block {
610 let _icx = push_ctxt("iter_structural_ty");
612 fn iter_variant(cx: block, repr: &adt::Repr, av: ValueRef,
613 variant: ty::VariantInfo,
614 tps: &[ty::t], f: val_and_ty_fn) -> block {
615 let _icx = push_ctxt("iter_variant");
619 for variant.args.iter().enumerate().advance |(i, &arg)| {
621 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
622 ty::subst_tps(tcx, tps, None, arg));
628 match ty::get(t).sty {
629 ty::ty_struct(*) => {
630 let repr = adt::represent_type(cx.ccx(), t);
631 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
632 for field_tys.iter().enumerate().advance |(i, field_ty)| {
633 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
634 cx = f(cx, llfld_a, field_ty.mt.ty);
638 ty::ty_estr(ty::vstore_fixed(_)) |
639 ty::ty_evec(_, ty::vstore_fixed(_)) => {
640 let (base, len) = tvec::get_base_and_len(cx, av, t);
641 cx = tvec::iter_vec_raw(cx, base, t, len, f);
643 ty::ty_tup(ref args) => {
644 let repr = adt::represent_type(cx.ccx(), t);
645 for args.iter().enumerate().advance |(i, arg)| {
646 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
647 cx = f(cx, llfld_a, *arg);
650 ty::ty_enum(tid, ref substs) => {
653 let repr = adt::represent_type(ccx, t);
654 let variants = ty::enum_variants(ccx.tcx, tid);
655 let n_variants = (*variants).len();
657 // NB: we must hit the discriminant first so that structural
658 // comparison know not to proceed when the discriminants differ.
660 match adt::trans_switch(cx, repr, av) {
661 (_match::single, None) => {
662 cx = iter_variant(cx, repr, av, variants[0],
665 (_match::switch, Some(lldiscrim_a)) => {
666 cx = f(cx, lldiscrim_a, ty::mk_int());
667 let unr_cx = sub_block(cx, "enum-iter-unr");
669 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
671 let next_cx = sub_block(cx, "enum-iter-next");
673 for (*variants).iter().advance |variant| {
675 sub_block(cx, ~"enum-iter-variant-" +
676 int::to_str(variant.disr_val));
678 iter_variant(variant_cx, repr, av, *variant,
680 match adt::trans_case(cx, repr, variant.disr_val) {
681 _match::single_result(r) => {
682 AddCase(llswitch, r.val, variant_cx.llbb)
684 _ => ccx.sess.unimpl("value from adt::trans_case \
685 in iter_structural_ty")
687 Br(variant_cx, next_cx.llbb);
691 _ => ccx.sess.unimpl("value from adt::trans_switch \
692 in iter_structural_ty")
695 _ => cx.sess().unimpl("type in iter_structural_ty")
700 pub fn cast_shift_expr_rhs(cx: block, op: ast::binop,
701 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
702 cast_shift_rhs(op, lhs, rhs,
703 |a,b| Trunc(cx, a, b),
704 |a,b| ZExt(cx, a, b))
707 pub fn cast_shift_const_rhs(op: ast::binop,
708 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
709 cast_shift_rhs(op, lhs, rhs,
710 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
711 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
714 pub fn cast_shift_rhs(op: ast::binop,
715 lhs: ValueRef, rhs: ValueRef,
716 trunc: &fn(ValueRef, Type) -> ValueRef,
717 zext: &fn(ValueRef, Type) -> ValueRef)
719 // Shifts may have any size int on the rhs
721 if ast_util::is_shift_binop(op) {
722 let rhs_llty = val_ty(rhs);
723 let lhs_llty = val_ty(lhs);
724 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
725 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
728 } else if lhs_sz > rhs_sz {
729 // FIXME (#1877: If shifting by negative
730 // values becomes not undefined then this is wrong.
741 pub fn fail_if_zero(cx: block, span: span, divrem: ast::binop,
742 rhs: ValueRef, rhs_t: ty::t) -> block {
743 let text = if divrem == ast::div {
744 @"attempted to divide by zero"
746 @"attempted remainder with a divisor of zero"
748 let is_zero = match ty::get(rhs_t).sty {
750 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
751 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
754 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
755 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
758 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
759 ty_to_str(cx.ccx().tcx, rhs_t));
762 do with_cond(cx, is_zero) |bcx| {
763 controlflow::trans_fail(bcx, Some(span), text)
767 pub fn null_env_ptr(bcx: block) -> ValueRef {
768 C_null(Type::opaque_box(bcx.ccx()).ptr_to())
771 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
773 let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
774 match ty::get(t).sty {
775 ty::ty_bare_fn(_) | ty::ty_closure(_) => {
776 let llty = type_of_fn_from_ty(ccx, t);
777 return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
778 lib::llvm::CCallConv, llty);
781 let llty = type_of(ccx, t);
782 return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
787 pub fn invoke(bcx: block, llfn: ValueRef, llargs: ~[ValueRef])
788 -> (ValueRef, block) {
789 let _icx = push_ctxt("invoke_");
791 return (C_null(Type::i8()), bcx);
794 match bcx.node_info {
795 None => debug!("invoke at ???"),
797 debug!("invoke at %s",
798 bcx.sess().codemap.span_to_str(node_info.span));
802 if need_invoke(bcx) {
804 debug!("invoking %x at %x",
805 ::core::cast::transmute(llfn),
806 ::core::cast::transmute(bcx.llbb));
807 for llargs.iter().advance |&llarg| {
808 debug!("arg: %x", ::core::cast::transmute(llarg));
811 let normal_bcx = sub_block(bcx, "normal return");
812 let llresult = Invoke(bcx,
816 get_landing_pad(bcx));
817 return (llresult, normal_bcx);
820 debug!("calling %x at %x",
821 ::core::cast::transmute(llfn),
822 ::core::cast::transmute(bcx.llbb));
823 for llargs.iter().advance |&llarg| {
824 debug!("arg: %x", ::core::cast::transmute(llarg));
827 let llresult = Call(bcx, llfn, llargs);
828 return (llresult, bcx);
832 pub fn need_invoke(bcx: block) -> bool {
833 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
837 // Avoid using invoke if we are already inside a landing pad.
842 if have_cached_lpad(bcx) {
846 // Walk the scopes to look for cleanups
850 block_scope(inf) => {
851 let inf = &mut *inf; // FIXME(#5074) workaround old borrowck
852 for inf.cleanups.iter().advance |cleanup| {
854 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
855 if cleanup_type == normal_exit_and_unwind {
864 cur = match cur.parent {
871 pub fn have_cached_lpad(bcx: block) -> bool {
873 do in_lpad_scope_cx(bcx) |inf| {
874 match inf.landing_pad {
875 Some(_) => res = true,
882 pub fn in_lpad_scope_cx(bcx: block, f: &fn(si: &mut scope_info)) {
887 block_scope(inf) => {
888 let len = { // FIXME(#5074) workaround old borrowck
892 if len > 0u || bcx.parent.is_none() {
900 bcx = block_parent(bcx);
904 pub fn get_landing_pad(bcx: block) -> BasicBlockRef {
905 let _icx = push_ctxt("get_landing_pad");
907 let mut cached = None;
908 let mut pad_bcx = bcx; // Guaranteed to be set below
909 do in_lpad_scope_cx(bcx) |inf| {
910 // If there is a valid landing pad still around, use it
911 match inf.landing_pad {
912 Some(target) => cached = Some(target),
914 pad_bcx = lpad_block(bcx, "unwind");
915 inf.landing_pad = Some(pad_bcx.llbb);
919 // Can't return from block above
920 match cached { Some(b) => return b, None => () }
921 // The landing pad return type (the type being propagated). Not sure what
922 // this represents but it's determined by the personality function and
923 // this is what the EH proposal example uses.
924 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
925 // The exception handling personality function. This is the C++
926 // personality function __gxx_personality_v0, wrapped in our naming
928 let personality = bcx.ccx().upcalls.rust_personality;
929 // The only landing pad clause will be 'cleanup'
930 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
931 // The landing pad block is a cleanup
932 SetCleanup(pad_bcx, llretval);
934 // Because we may have unwound across a stack boundary, we must call into
935 // the runtime to figure out which stack segment we are on and place the
936 // stack limit back into the TLS.
937 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
939 // We store the retval in a function-central alloca, so that calls to
940 // Resume can find it.
941 match bcx.fcx.personality {
942 Some(addr) => Store(pad_bcx, llretval, addr),
944 let addr = alloca(pad_bcx, val_ty(llretval));
945 bcx.fcx.personality = Some(addr);
946 Store(pad_bcx, llretval, addr);
950 // Unwind all parent scopes, and finish with a Resume instr
951 cleanup_and_leave(pad_bcx, None, None);
955 pub fn find_bcx_for_scope(bcx: block, scope_id: ast::node_id) -> block {
956 let mut bcx_sid = bcx;
958 bcx_sid = match bcx_sid.node_info {
959 Some(NodeInfo { id, _ }) if id == scope_id => {
963 // FIXME(#6268, #6248) hacky cleanup for nested method calls
964 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
969 match bcx_sid.parent {
970 None => bcx.tcx().sess.bug(
971 fmt!("no enclosing scope with id %d", scope_id)),
972 Some(bcx_par) => bcx_par
980 pub fn do_spill(bcx: block, v: ValueRef, t: ty::t) -> ValueRef {
981 if ty::type_is_bot(t) {
982 return C_null(Type::i8p());
984 let llptr = alloc_ty(bcx, t);
985 Store(bcx, v, llptr);
989 // Since this function does *not* root, it is the caller's responsibility to
990 // ensure that the referent is pointed to by a root.
991 pub fn do_spill_noroot(cx: block, v: ValueRef) -> ValueRef {
992 let llptr = alloca(cx, val_ty(v));
997 pub fn spill_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
998 let _icx = push_ctxt("spill_if_immediate");
999 if ty::type_is_immediate(t) { return do_spill(cx, v, t); }
1003 pub fn load_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
1004 let _icx = push_ctxt("load_if_immediate");
1005 if ty::type_is_immediate(t) { return Load(cx, v); }
1009 pub fn trans_trace(bcx: block, sp_opt: Option<span>, trace_str: @str) {
1010 if !bcx.sess().trace() { return; }
1011 let _icx = push_ctxt("trans_trace");
1012 add_comment(bcx, trace_str);
1013 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1014 let (V_filename, V_line) = match sp_opt {
1016 let sess = bcx.sess();
1017 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1018 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1021 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1024 let ccx = bcx.ccx();
1025 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1026 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1027 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1028 Call(bcx, ccx.upcalls.trace, args);
1031 pub fn build_return(bcx: block) {
1032 let _icx = push_ctxt("build_return");
1033 Br(bcx, bcx.fcx.llreturn);
1036 pub fn ignore_lhs(_bcx: block, local: @ast::local) -> bool {
1037 match local.node.pat.node {
1038 ast::pat_wild => true, _ => false
1042 pub fn init_local(bcx: block, local: @ast::local) -> block {
1044 debug!("init_local(bcx=%s, local.id=%?)",
1045 bcx.to_str(), local.node.id);
1046 let _indenter = indenter();
1048 let _icx = push_ctxt("init_local");
1049 let ty = node_id_type(bcx, local.node.id);
1051 debug!("ty=%s", bcx.ty_to_str(ty));
1053 if ignore_lhs(bcx, local) {
1054 // Handle let _ = e; just like e;
1055 match local.node.init {
1057 return expr::trans_into(bcx, init, expr::Ignore);
1059 None => { return bcx; }
1063 let llptr = match bcx.fcx.lllocals.find_copy(&local.node.id) {
1066 bcx.tcx().sess.span_bug(local.span,
1067 "init_local: Someone forgot to document why it's\
1068 safe to assume local.node.init must be local_mem!");
1073 match local.node.init {
1075 bcx = expr::trans_into(bcx, init, expr::SaveIn(llptr));
1078 zero_mem(bcx, llptr, ty);
1082 // Make a note to drop this slot on the way out.
1083 debug!("adding clean for %?/%s to bcx=%s",
1084 local.node.id, bcx.ty_to_str(ty),
1086 add_clean(bcx, llptr, ty);
1088 return _match::bind_irrefutable_pat(bcx,
1095 pub fn trans_stmt(cx: block, s: &ast::stmt) -> block {
1096 let _icx = push_ctxt("trans_stmt");
1097 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1099 if cx.sess().asm_comments() {
1100 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1104 debuginfo::update_source_pos(cx, s.span);
1107 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1108 bcx = expr::trans_into(cx, e, expr::Ignore);
1110 ast::stmt_decl(d, _) => {
1112 ast::decl_local(ref local) => {
1113 bcx = init_local(bcx, *local);
1114 if cx.sess().opts.extra_debuginfo
1115 && fcx_has_nonzero_span(bcx.fcx) {
1116 debuginfo::create_local_var(bcx, *local);
1119 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1122 ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1128 // You probably don't want to use this one. See the
1129 // next three functions instead.
1130 pub fn new_block(cx: fn_ctxt, parent: Option<block>, kind: block_kind,
1131 is_lpad: bool, name: &str, opt_node_info: Option<NodeInfo>)
1134 let s = if cx.ccx.sess.opts.save_temps || cx.ccx.sess.opts.debuginfo {
1135 (cx.ccx.names)(name)
1137 special_idents::invalid
1140 let llbb = str::as_c_str(cx.ccx.sess.str_of(s), |buf| {
1141 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1143 let bcx = mk_block(llbb,
1149 for parent.iter().advance |cx| {
1150 if cx.unreachable { Unreachable(bcx); }
1156 pub fn simple_block_scope() -> block_kind {
1157 block_scope(@mut scope_info {
1166 // Use this when you're at the top block of a function or the like.
1167 pub fn top_scope_block(fcx: fn_ctxt, opt_node_info: Option<NodeInfo>)
1169 return new_block(fcx, None, simple_block_scope(), false,
1170 "function top level", opt_node_info);
1173 pub fn scope_block(bcx: block,
1174 opt_node_info: Option<NodeInfo>,
1176 return new_block(bcx.fcx, Some(bcx), simple_block_scope(), bcx.is_lpad,
1180 pub fn loop_scope_block(bcx: block,
1182 loop_label: Option<ident>,
1184 opt_node_info: Option<NodeInfo>) -> block {
1185 return new_block(bcx.fcx, Some(bcx), block_scope(@mut scope_info {
1186 loop_break: Some(loop_break),
1187 loop_label: loop_label,
1191 }), bcx.is_lpad, n, opt_node_info);
1194 // Use this when creating a block for the inside of a landing pad.
1195 pub fn lpad_block(bcx: block, n: &str) -> block {
1196 new_block(bcx.fcx, Some(bcx), block_non_scope, true, n, None)
1199 // Use this when you're making a general CFG BB within a scope.
1200 pub fn sub_block(bcx: block, n: &str) -> block {
1201 new_block(bcx.fcx, Some(bcx), block_non_scope, bcx.is_lpad, n, None)
1204 pub fn raw_block(fcx: fn_ctxt, is_lpad: bool, llbb: BasicBlockRef) -> block {
1205 mk_block(llbb, None, block_non_scope, is_lpad, None, fcx)
1209 // trans_block_cleanups: Go through all the cleanups attached to this
1210 // block and execute them.
1212 // When translating a block that introduces new variables during its scope, we
1213 // need to make sure those variables go out of scope when the block ends. We
1214 // do that by running a 'cleanup' function for each variable.
1215 // trans_block_cleanups runs all the cleanup functions for the block.
1216 pub fn trans_block_cleanups(bcx: block, cleanups: ~[cleanup]) -> block {
1217 trans_block_cleanups_(bcx, cleanups, false)
1220 pub fn trans_block_cleanups_(bcx: block,
1221 cleanups: &[cleanup],
1222 /* cleanup_cx: block, */
1223 is_lpad: bool) -> block {
1224 let _icx = push_ctxt("trans_block_cleanups");
1225 // NB: Don't short-circuit even if this block is unreachable because
1226 // GC-based cleanup needs to the see that the roots are live.
1228 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1229 if bcx.unreachable && !no_lpads { return bcx; }
1231 for cleanups.rev_iter().advance |cu| {
1233 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1234 // Some types don't need to be cleaned up during
1235 // landing pads because they can be freed en mass later
1236 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1245 // In the last argument, Some(block) mean jump to this block, and none means
1246 // this is a landing pad and leaving should be accomplished with a resume
1248 pub fn cleanup_and_leave(bcx: block,
1249 upto: Option<BasicBlockRef>,
1250 leave: Option<BasicBlockRef>) {
1251 let _icx = push_ctxt("cleanup_and_leave");
1254 let is_lpad = leave == None;
1256 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1258 if bcx.sess().trace() {
1261 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1265 block_scope(inf) if !inf.empty_cleanups() => {
1266 let (sub_cx, dest, inf_cleanups) = {
1267 let inf = &mut *inf;
1269 let mut dest = None;
1271 let r = vec::rfind((*inf).cleanup_paths, |cp| cp.target == leave);
1272 for r.iter().advance |cp| {
1273 if cp.size == inf.cleanups.len() {
1279 dest = Some(cp.dest);
1282 let sub_cx = sub_block(bcx, "cleanup");
1283 Br(bcx, sub_cx.llbb);
1284 inf.cleanup_paths.push(cleanup_path {
1286 size: inf.cleanups.len(),
1289 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1291 bcx = trans_block_cleanups_(sub_cx,
1294 for dest.iter().advance |&dest| {
1303 Some(bb) => { if cur.llbb == bb { break; } }
1306 cur = match cur.parent {
1308 None => { assert!(upto.is_none()); break; }
1312 Some(target) => Br(bcx, target),
1313 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.get())); }
1317 pub fn cleanup_and_Br(bcx: block, upto: block, target: BasicBlockRef) {
1318 let _icx = push_ctxt("cleanup_and_Br");
1319 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1322 pub fn leave_block(bcx: block, out_of: block) -> block {
1323 let _icx = push_ctxt("leave_block");
1324 let next_cx = sub_block(block_parent(out_of), "next");
1325 if bcx.unreachable { Unreachable(next_cx); }
1326 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1330 pub fn with_scope(bcx: block,
1331 opt_node_info: Option<NodeInfo>,
1333 f: &fn(block) -> block) -> block {
1334 let _icx = push_ctxt("with_scope");
1336 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1337 bcx.to_str(), opt_node_info, name);
1338 let _indenter = indenter();
1340 let scope_cx = scope_block(bcx, opt_node_info, name);
1341 Br(bcx, scope_cx.llbb);
1342 leave_block(f(scope_cx), scope_cx)
1345 pub fn with_scope_result(bcx: block,
1346 opt_node_info: Option<NodeInfo>,
1348 f: &fn(block) -> Result) -> Result {
1349 let _icx = push_ctxt("with_scope_result");
1350 let scope_cx = scope_block(bcx, opt_node_info, name);
1351 Br(bcx, scope_cx.llbb);
1352 let Result {bcx, val} = f(scope_cx);
1353 rslt(leave_block(bcx, scope_cx), val)
1356 pub fn with_scope_datumblock(bcx: block, opt_node_info: Option<NodeInfo>,
1357 name: &str, f: &fn(block) -> datum::DatumBlock)
1358 -> datum::DatumBlock {
1359 use middle::trans::datum::DatumBlock;
1361 let _icx = push_ctxt("with_scope_result");
1362 let scope_cx = scope_block(bcx, opt_node_info, name);
1363 Br(bcx, scope_cx.llbb);
1364 let DatumBlock {bcx, datum} = f(scope_cx);
1365 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1368 pub fn block_locals(b: &ast::blk, it: &fn(@ast::local)) {
1369 for b.node.stmts.iter().advance |s| {
1371 ast::stmt_decl(d, _) => {
1373 ast::decl_local(ref local) => it(*local),
1374 _ => {} /* fall through */
1377 _ => {} /* fall through */
1382 pub fn alloc_local(cx: block, local: @ast::local) -> block {
1383 let _icx = push_ctxt("alloc_local");
1384 let t = node_id_type(cx, local.node.id);
1385 let simple_name = match local.node.pat.node {
1386 ast::pat_ident(_, pth, None) => Some(path_to_ident(pth)),
1389 let val = alloc_ty(cx, t);
1390 if cx.sess().opts.debuginfo {
1391 for simple_name.iter().advance |name| {
1392 str::as_c_str(cx.ccx().sess.str_of(*name), |buf| {
1394 llvm::LLVMSetValueName(val, buf)
1399 cx.fcx.lllocals.insert(local.node.id, val);
1404 pub fn with_cond(bcx: block, val: ValueRef, f: &fn(block) -> block) -> block {
1405 let _icx = push_ctxt("with_cond");
1406 let next_cx = base::sub_block(bcx, "next");
1407 let cond_cx = base::sub_block(bcx, "cond");
1408 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1409 let after_cx = f(cond_cx);
1410 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1414 pub fn call_memcpy(cx: block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1415 let _icx = push_ctxt("call_memcpy");
1417 let key = match ccx.sess.targ_cfg.arch {
1418 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1419 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1421 let memcpy = ccx.intrinsics.get_copy(&key);
1422 let src_ptr = PointerCast(cx, src, Type::i8p());
1423 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1424 let size = IntCast(cx, n_bytes, ccx.int_type);
1425 let align = C_i32(align as i32);
1426 let volatile = C_i1(false);
1427 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1430 pub fn memcpy_ty(bcx: block, dst: ValueRef, src: ValueRef, t: ty::t) {
1431 let _icx = push_ctxt("memcpy_ty");
1432 let ccx = bcx.ccx();
1433 if ty::type_is_structural(t) {
1434 let llty = type_of::type_of(ccx, t);
1435 let llsz = llsize_of(ccx, llty);
1436 let llalign = llalign_of_min(ccx, llty);
1437 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1439 Store(bcx, Load(bcx, src), dst);
1443 pub fn zero_mem(cx: block, llptr: ValueRef, t: ty::t) {
1444 let _icx = push_ctxt("zero_mem");
1447 let llty = type_of::type_of(ccx, t);
1448 memzero(bcx, llptr, llty);
1451 // Always use this function instead of storing a zero constant to the memory
1452 // in question. If you store a zero constant, LLVM will drown in vreg
1453 // allocation for large data structures, and the generated code will be
1454 // awful. (A telltale sign of this is large quantities of
1455 // `mov [byte ptr foo],0` in the generated code.)
1456 pub fn memzero(cx: block, llptr: ValueRef, ty: Type) {
1457 let _icx = push_ctxt("memzero");
1460 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1461 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1462 X86_64 => "llvm.memset.p0i8.i64"
1465 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1466 let llptr = PointerCast(cx, llptr, Type::i8().ptr_to());
1467 let llzeroval = C_u8(0);
1468 let size = IntCast(cx, machine::llsize_of(ccx, ty), ccx.int_type);
1469 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1470 let volatile = C_i1(false);
1471 Call(cx, llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1474 pub fn alloc_ty(bcx: block, t: ty::t) -> ValueRef {
1475 let _icx = push_ctxt("alloc_ty");
1476 let ccx = bcx.ccx();
1477 let ty = type_of::type_of(ccx, t);
1478 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1479 let val = alloca(bcx, ty);
1483 pub fn alloca(cx: block, ty: Type) -> ValueRef {
1484 alloca_maybe_zeroed(cx, ty, false)
1487 pub fn alloca_maybe_zeroed(cx: block, ty: Type, zero: bool) -> ValueRef {
1488 let _icx = push_ctxt("alloca");
1491 return llvm::LLVMGetUndef(ty.to_ref());
1494 let initcx = base::raw_block(cx.fcx, false, cx.fcx.llstaticallocas);
1495 let p = Alloca(initcx, ty);
1496 if zero { memzero(initcx, p, ty); }
1500 pub fn arrayalloca(cx: block, ty: Type, v: ValueRef) -> ValueRef {
1501 let _icx = push_ctxt("arrayalloca");
1504 return llvm::LLVMGetUndef(ty.to_ref());
1507 return ArrayAlloca(base::raw_block(cx.fcx, false, cx.fcx.llstaticallocas), ty, v);
1510 pub struct BasicBlocks {
1515 // Creates the standard set of basic blocks for a function
1516 pub fn mk_standard_basic_blocks(llfn: ValueRef) -> BasicBlocks {
1518 let cx = task_llcx();
1520 sa: str::as_c_str("static_allocas",
1521 |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)),
1522 rt: str::as_c_str("return",
1523 |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf))
1528 // Creates and returns space for, or returns the argument representing, the
1529 // slot where the return value of the function must go.
1530 pub fn make_return_pointer(fcx: fn_ctxt, output_type: ty::t) -> ValueRef {
1532 if !ty::type_is_immediate(output_type) {
1533 llvm::LLVMGetParam(fcx.llfn, 0)
1535 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1536 alloca(raw_block(fcx, false, fcx.llstaticallocas), lloutputtype)
1541 // NB: must keep 4 fns in sync:
1544 // - create_llargs_for_fn_args.
1547 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1552 impl_id: Option<ast::def_id>,
1553 param_substs: Option<@param_substs>,
1556 for param_substs.iter().advance |p| { p.validate(); }
1558 debug!("new_fn_ctxt_w_id(path=%s, id=%?, impl_id=%?, \
1560 path_str(ccx.sess, path),
1563 param_substs.repr(ccx.tcx));
1565 let llbbs = mk_standard_basic_blocks(llfndecl);
1567 let substd_output_type = match param_substs {
1568 None => output_type,
1570 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1573 let is_immediate = ty::type_is_immediate(substd_output_type);
1574 let fcx = @mut fn_ctxt_ {
1577 llvm::LLVMGetUndef(Type::i8p().to_ref())
1580 llstaticallocas: llbbs.sa,
1586 has_immediate_return_value: is_immediate,
1587 llargs: @mut HashMap::new(),
1588 lllocals: @mut HashMap::new(),
1589 llupvars: @mut HashMap::new(),
1592 param_substs: param_substs,
1597 fcx.llenv = unsafe {
1598 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1600 if !ty::type_is_nil(substd_output_type) {
1601 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1606 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1612 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, None, None, sp)
1615 // NB: must keep 4 fns in sync:
1618 // - create_llargs_for_fn_args.
1622 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1623 // allocas created for them.
1625 // When we translate a function, we need to map its incoming arguments to the
1626 // spaces that have been created for them (by code in the llallocas field of
1627 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1628 // field of the fn_ctxt with
1629 pub fn create_llargs_for_fn_args(cx: fn_ctxt,
1633 let _icx = push_ctxt("create_llargs_for_fn_args");
1637 cx.llself = Some(ValSelfData {
1643 impl_owned_self(tt) => {
1644 cx.llself = Some(ValSelfData {
1653 // Return an array containing the ValueRefs that we get from
1654 // llvm::LLVMGetParam for each argument.
1655 vec::from_fn(args.len(), |i| {
1657 let arg_n = cx.arg_pos(i);
1659 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1662 // `~` pointers never alias other parameters, because ownership was transferred
1663 ast::ty_uniq(_) => {
1664 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1666 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1667 // those in the other parameters and then mark it as `noalias` if there aren't any
1676 pub fn copy_args_to_allocas(fcx: fn_ctxt,
1679 raw_llargs: &[ValueRef],
1680 arg_tys: &[ty::t]) -> block {
1681 let _icx = push_ctxt("copy_args_to_allocas");
1686 // We really should do this regardless of whether self is owned, but
1687 // it doesn't work right with default method impls yet. (FIXME: #2794)
1689 let self_val = if datum::appropriate_mode(slf.t).is_by_value() {
1690 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1691 let alloc = alloc_ty(bcx, slf.t);
1692 Store(bcx, tmp, alloc);
1695 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1698 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1699 add_clean(bcx, self_val, slf.t);
1705 for uint::range(0, arg_tys.len()) |arg_n| {
1706 let arg_ty = arg_tys[arg_n];
1707 let raw_llarg = raw_llargs[arg_n];
1708 let arg_id = args[arg_n].id;
1710 // For certain mode/type combinations, the raw llarg values are passed
1711 // by value. However, within the fn body itself, we want to always
1712 // have all locals and arguments be by-ref so that we can cancel the
1713 // cleanup and for better interaction with LLVM's debug info. So, if
1714 // the argument would be passed by value, we store it into an alloca.
1715 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1716 // the event it's not truly needed.
1717 // only by value if immediate:
1718 let llarg = if datum::appropriate_mode(arg_ty).is_by_value() {
1719 let alloc = alloc_ty(bcx, arg_ty);
1720 Store(bcx, raw_llarg, alloc);
1726 add_clean(bcx, llarg, arg_ty);
1728 bcx = _match::bind_irrefutable_pat(bcx,
1732 _match::BindArgument);
1734 fcx.llargs.insert(arg_id, llarg);
1736 if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1737 debuginfo::create_arg(bcx, args[arg_n], args[arg_n].ty.span);
1744 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1745 // and builds the return block.
1746 pub fn finish_fn(fcx: fn_ctxt, lltop: BasicBlockRef) {
1747 let _icx = push_ctxt("finish_fn");
1748 tie_up_header_blocks(fcx, lltop);
1749 build_return_block(fcx);
1752 // Builds the return block for a function.
1753 pub fn build_return_block(fcx: fn_ctxt) {
1754 let ret_cx = raw_block(fcx, false, fcx.llreturn);
1756 // Return the value if this function immediate; otherwise, return void.
1757 if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
1758 Ret(ret_cx, Load(ret_cx, fcx.llretptr.get()))
1764 pub fn tie_up_header_blocks(fcx: fn_ctxt, lltop: BasicBlockRef) {
1765 let _icx = push_ctxt("tie_up_header_blocks");
1766 match fcx.llloadenv {
1768 Br(raw_block(fcx, false, fcx.llstaticallocas), ll);
1769 Br(raw_block(fcx, false, ll), lltop);
1772 Br(raw_block(fcx, false, fcx.llstaticallocas), lltop);
1777 pub enum self_arg { impl_self(ty::t), impl_owned_self(ty::t), no_self, }
1779 // trans_closure: Builds an LLVM function out of a source function.
1780 // If the function closes over its environment a closure will be
1782 pub fn trans_closure(ccx: @mut CrateContext,
1784 decl: &ast::fn_decl,
1788 param_substs: Option<@param_substs>,
1790 impl_id: Option<ast::def_id>,
1791 attributes: &[ast::attribute],
1793 maybe_load_env: &fn(fn_ctxt),
1794 finish: &fn(block)) {
1795 ccx.stats.n_closures += 1;
1796 let _icx = push_ctxt("trans_closure");
1797 set_uwtable(llfndecl);
1799 debug!("trans_closure(..., param_substs=%s)",
1800 param_substs.repr(ccx.tcx));
1802 // Set up arguments to the function.
1803 let fcx = new_fn_ctxt_w_id(ccx,
1811 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1813 // Set the fixed stack segment flag if necessary.
1814 if attr::attrs_contains_name(attributes, "fixed_stack_segment") {
1815 set_no_inline(fcx.llfn);
1816 set_fixed_stack_segment(fcx.llfn);
1819 // Create the first basic block in the function and keep a handle on it to
1820 // pass to finish_fn later.
1821 let bcx_top = top_scope_block(fcx, body.info());
1822 let mut bcx = bcx_top;
1823 let lltop = bcx.llbb;
1824 let block_ty = node_id_type(bcx, body.node.id);
1826 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1827 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1829 maybe_load_env(fcx);
1831 // This call to trans_block is the place where we bridge between
1832 // translation calls that don't have a return value (trans_crate,
1833 // trans_mod, trans_item, et cetera) and those that do
1834 // (trans_block, trans_expr, et cetera).
1835 if body.node.expr.is_none() || ty::type_is_bot(block_ty) ||
1836 ty::type_is_nil(block_ty)
1838 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1840 let dest = expr::SaveIn(fcx.llretptr.get());
1841 bcx = controlflow::trans_block(bcx, body, dest);
1845 cleanup_and_Br(bcx, bcx_top, fcx.llreturn);
1847 // Put return block after all other blocks.
1848 // This somewhat improves single-stepping experience in debugger.
1850 llvm::LLVMMoveBasicBlockAfter(fcx.llreturn, bcx.llbb);
1853 // Insert the mandatory first few basic blocks before lltop.
1854 finish_fn(fcx, lltop);
1857 // trans_fn: creates an LLVM function corresponding to a source language
1859 pub fn trans_fn(ccx: @mut CrateContext,
1861 decl: &ast::fn_decl,
1865 param_substs: Option<@param_substs>,
1867 impl_id: Option<ast::def_id>,
1868 attrs: &[ast::attribute]) {
1869 let do_time = ccx.sess.trans_stats();
1870 let start = if do_time { time::get_time() }
1871 else { time::Timespec::new(0, 0) };
1872 debug!("trans_fn(self_arg=%?, param_substs=%s)",
1874 param_substs.repr(ccx.tcx));
1875 let _icx = push_ctxt("trans_fn");
1876 ccx.stats.n_fns += 1;
1877 let the_path_str = path_str(ccx.sess, path);
1878 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1891 if ccx.sess.opts.extra_debuginfo
1892 && fcx_has_nonzero_span(fcx) {
1893 debuginfo::create_function(fcx);
1898 let end = time::get_time();
1899 ccx.log_fn_time(the_path_str, start, end);
1903 pub fn trans_enum_variant(ccx: @mut CrateContext,
1904 enum_id: ast::node_id,
1905 variant: &ast::variant,
1906 args: &[ast::variant_arg],
1908 param_substs: Option<@param_substs>,
1909 llfndecl: ValueRef) {
1910 let _icx = push_ctxt("trans_enum_variant");
1911 // Translate variant arguments to function arguments.
1912 let fn_args = do args.map |varg| {
1916 pat: ast_util::ident_to_pat(
1917 ccx.tcx.sess.next_node_id(),
1918 codemap::dummy_sp(),
1919 special_idents::arg),
1924 let ty_param_substs = match param_substs {
1925 Some(ref substs) => { copy substs.tys }
1928 let enum_ty = ty::subst_tps(ccx.tcx,
1931 ty::node_id_to_type(ccx.tcx, enum_id));
1932 let fcx = new_fn_ctxt_w_id(ccx,
1941 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
1942 let bcx = top_scope_block(fcx, None);
1943 let lltop = bcx.llbb;
1944 let arg_tys = ty::ty_fn_args(node_id_type(bcx, variant.node.id));
1945 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
1947 // XXX is there a better way to reconstruct the ty::t?
1948 let repr = adt::represent_type(ccx, enum_ty);
1950 debug!("trans_enum_variant: name=%s tps=%s repr=%? enum_ty=%s",
1951 unsafe { str::raw::from_c_str(llvm::LLVMGetValueName(llfndecl)) },
1952 ~"[" + ty_param_substs.map(|&t| ty_to_str(ccx.tcx, t)).connect(", ") + "]",
1953 repr, ty_to_str(ccx.tcx, enum_ty));
1955 adt::trans_start_init(bcx, repr, fcx.llretptr.get(), disr);
1956 for args.iter().enumerate().advance |(i, va)| {
1957 let lldestptr = adt::trans_field_ptr(bcx,
1963 // If this argument to this function is a enum, it'll have come in to
1964 // this function as an opaque blob due to the way that type_of()
1965 // works. So we have to cast to the destination's view of the type.
1966 let llarg = match fcx.llargs.find(&va.id) {
1968 _ => fail!("trans_enum_variant: how do we know this works?"),
1970 let arg_ty = arg_tys[i];
1971 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
1974 finish_fn(fcx, lltop);
1977 // NB: In theory this should be merged with the function above. But the AST
1978 // structures are completely different, so very little code would be shared.
1979 pub fn trans_tuple_struct(ccx: @mut CrateContext,
1980 fields: &[@ast::struct_field],
1981 ctor_id: ast::node_id,
1982 param_substs: Option<@param_substs>,
1983 llfndecl: ValueRef) {
1984 let _icx = push_ctxt("trans_tuple_struct");
1986 // Translate struct fields to function arguments.
1987 let fn_args = do fields.map |field| {
1991 pat: ast_util::ident_to_pat(ccx.tcx.sess.next_node_id(),
1992 codemap::dummy_sp(),
1993 special_idents::arg),
1998 // XXX is there a better way to reconstruct the ty::t?
1999 let ty_param_substs = match param_substs {
2000 Some(ref substs) => { copy substs.tys }
2003 let ctor_ty = ty::subst_tps(ccx.tcx, ty_param_substs, None,
2004 ty::node_id_to_type(ccx.tcx, ctor_id));
2005 let tup_ty = match ty::get(ctor_ty).sty {
2006 ty::ty_bare_fn(ref bft) => bft.sig.output,
2007 _ => ccx.sess.bug(fmt!("trans_tuple_struct: unexpected ctor \
2009 ty_to_str(ccx.tcx, ctor_ty)))
2012 let fcx = new_fn_ctxt_w_id(ccx,
2021 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2023 let bcx = top_scope_block(fcx, None);
2024 let lltop = bcx.llbb;
2025 let arg_tys = ty::ty_fn_args(node_id_type(bcx, ctor_id));
2026 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2028 let repr = adt::represent_type(ccx, tup_ty);
2029 adt::trans_start_init(bcx, repr, fcx.llretptr.get(), 0);
2031 for fields.iter().enumerate().advance |(i, field)| {
2032 let lldestptr = adt::trans_field_ptr(bcx,
2037 let llarg = fcx.llargs.get_copy(&field.node.id);
2038 let arg_ty = arg_tys[i];
2039 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2043 finish_fn(fcx, lltop);
2046 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2047 id: ast::node_id, vi: @~[ty::VariantInfo],
2049 for enum_definition.variants.iter().advance |variant| {
2050 let disr_val = vi[*i].disr_val;
2053 match variant.node.kind {
2054 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2055 let llfn = get_item_val(ccx, variant.node.id);
2056 trans_enum_variant(ccx, id, variant, *args,
2057 disr_val, None, llfn);
2059 ast::tuple_variant_kind(_) => {
2062 ast::struct_variant_kind(struct_def) => {
2063 trans_struct_def(ccx, struct_def);
2069 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2070 let _icx = push_ctxt("trans_item");
2071 let path = match ccx.tcx.items.get_copy(&item.id) {
2072 ast_map::node_item(_, p) => p,
2074 _ => fail!("trans_item"),
2077 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2078 if purity == ast::extern_fn {
2079 let llfndecl = get_item_val(ccx, item.id);
2080 foreign::trans_foreign_fn(ccx,
2081 vec::append(/*bad*/copy *path,
2082 [path_name(item.ident)]),
2087 } else if !generics.is_type_parameterized() {
2088 let llfndecl = get_item_val(ccx, item.id);
2090 vec::append(/*bad*/copy *path, [path_name(item.ident)]),
2100 for body.node.stmts.iter().advance |stmt| {
2102 ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2111 ast::item_impl(ref generics, _, _, ref ms) => {
2112 meth::trans_impl(ccx, /*bad*/copy *path, item.ident, *ms,
2113 generics, None, item.id);
2115 ast::item_mod(ref m) => {
2118 ast::item_enum(ref enum_definition, ref generics) => {
2119 if !generics.is_type_parameterized() {
2120 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2122 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2125 ast::item_static(_, m, expr) => {
2126 consts::trans_const(ccx, m, item.id);
2127 // Do static_assert checking. It can't really be done much earlier because we need to get
2128 // the value of the bool out of LLVM
2129 for item.attrs.iter().advance |attr| {
2130 match attr.node.value.node {
2131 ast::meta_word(x) => {
2132 if x.slice(0, x.len()) == "static_assert" {
2133 if m == ast::m_mutbl {
2134 ccx.sess.span_fatal(expr.span,
2135 "cannot have static_assert \
2136 on a mutable static");
2138 let v = ccx.const_values.get_copy(&item.id);
2140 if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2141 ccx.sess.span_fatal(expr.span, "static assertion failed");
2150 ast::item_foreign_mod(ref foreign_mod) => {
2151 foreign::trans_foreign_mod(ccx, path, foreign_mod);
2153 ast::item_struct(struct_def, ref generics) => {
2154 if !generics.is_type_parameterized() {
2155 trans_struct_def(ccx, struct_def);
2158 _ => {/* fall through */ }
2162 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2163 // If this is a tuple-like struct, translate the constructor.
2164 match struct_def.ctor_id {
2165 // We only need to translate a constructor if there are fields;
2166 // otherwise this is a unit-like struct.
2167 Some(ctor_id) if struct_def.fields.len() > 0 => {
2168 let llfndecl = get_item_val(ccx, ctor_id);
2169 trans_tuple_struct(ccx, struct_def.fields,
2170 ctor_id, None, llfndecl);
2172 Some(_) | None => {}
2176 // Translate a module. Doing this amounts to translating the items in the
2177 // module; there ends up being no artifact (aside from linkage names) of
2178 // separate modules in the compiled program. That's because modules exist
2179 // only as a convenience for humans working with the code, to organize names
2180 // and control visibility.
2181 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2182 let _icx = push_ctxt("trans_mod");
2183 for m.items.iter().advance |item| {
2184 trans_item(ccx, *item);
2188 pub fn register_fn(ccx: @mut CrateContext,
2191 node_id: ast::node_id,
2192 attrs: &[ast::attribute])
2194 let t = ty::node_id_to_type(ccx.tcx, node_id);
2195 register_fn_full(ccx, sp, path, node_id, attrs, t)
2198 pub fn register_fn_full(ccx: @mut CrateContext,
2201 node_id: ast::node_id,
2202 attrs: &[ast::attribute],
2205 let llfty = type_of_fn_from_ty(ccx, node_type);
2206 register_fn_fuller(ccx, sp, path, node_id, attrs, node_type,
2207 lib::llvm::CCallConv, llfty)
2210 pub fn register_fn_fuller(ccx: @mut CrateContext,
2213 node_id: ast::node_id,
2214 attrs: &[ast::attribute],
2216 cc: lib::llvm::CallConv,
2219 debug!("register_fn_fuller creating fn for item %d with path %s",
2221 ast_map::path_to_str(path, token::get_ident_interner()));
2223 let ps = if attr::attrs_contains_name(attrs, "no_mangle") {
2224 path_elt_to_str(*path.last(), token::get_ident_interner())
2226 mangle_exported_name(ccx, /*bad*/copy path, node_type)
2229 let llfn = decl_fn(ccx.llmod, ps, cc, fn_ty);
2230 ccx.item_symbols.insert(node_id, ps);
2232 // FIXME #4404 android JNI hacks
2233 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2234 (*ccx.sess.building_library &&
2235 ccx.sess.targ_cfg.os == session::os_android));
2237 create_entry_wrapper(ccx, sp, llfn);
2242 pub fn is_entry_fn(sess: &Session, node_id: ast::node_id) -> bool {
2243 match *sess.entry_fn {
2244 Some((entry_id, _)) => node_id == entry_id,
2249 // Create a _rust_main(args: ~[str]) function which will be called from the
2250 // runtime rust_start function
2251 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2252 _sp: span, main_llfn: ValueRef) {
2253 let et = ccx.sess.entry_type.unwrap();
2254 if et == session::EntryMain {
2255 let llfn = create_main(ccx, main_llfn);
2256 create_entry_fn(ccx, llfn, true);
2258 create_entry_fn(ccx, main_llfn, false);
2261 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2262 let nt = ty::mk_nil();
2264 let llfty = type_of_fn(ccx, [], nt);
2265 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2266 lib::llvm::CCallConv, llfty);
2268 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2270 // the args vector built in create_entry_fn will need
2271 // be updated if this assertion starts to fail.
2272 assert!(fcx.has_immediate_return_value);
2274 let bcx = top_scope_block(fcx, None);
2275 let lltop = bcx.llbb;
2278 let llenvarg = unsafe {
2279 let env_arg = fcx.env_arg_pos();
2280 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2282 let args = ~[llenvarg];
2283 Call(bcx, main_llfn, args);
2286 finish_fn(fcx, lltop);
2290 fn create_entry_fn(ccx: @mut CrateContext,
2291 rust_main: ValueRef,
2292 use_start_lang_item: bool) {
2293 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()], &ccx.int_type);
2295 // FIXME #4404 android JNI hacks
2296 let llfn = if *ccx.sess.building_library {
2297 decl_cdecl_fn(ccx.llmod, "amain", llfty)
2299 let main_name = match ccx.sess.targ_cfg.os {
2300 session::os_win32 => ~"WinMain@16",
2303 decl_cdecl_fn(ccx.llmod, main_name, llfty)
2305 let llbb = str::as_c_str("top", |buf| {
2307 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2310 let bld = ccx.builder.B;
2312 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2314 let start_def_id = ccx.tcx.lang_items.start_fn();
2315 if start_def_id.crate != ast::local_crate {
2316 let start_fn_type = csearch::get_type(ccx.tcx,
2318 trans_external_path(ccx, start_def_id, start_fn_type);
2321 let crate_map = ccx.crate_map;
2322 let opaque_crate_map = do "crate_map".as_c_str |buf| {
2323 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2326 let (start_fn, args) = if use_start_lang_item {
2327 let start_def_id = ccx.tcx.lang_items.start_fn();
2328 let start_fn = if start_def_id.crate == ast::local_crate {
2329 get_item_val(ccx, start_def_id.node)
2331 let start_fn_type = csearch::get_type(ccx.tcx,
2333 trans_external_path(ccx, start_def_id, start_fn_type)
2337 let opaque_rust_main = do "rust_main".as_c_str |buf| {
2338 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2342 C_null(Type::opaque_box(ccx).ptr_to()),
2344 llvm::LLVMGetParam(llfn, 0),
2345 llvm::LLVMGetParam(llfn, 1),
2351 debug!("using user-defined start fn");
2354 C_null(Type::opaque_box(ccx).ptr_to()),
2355 llvm::LLVMGetParam(llfn, 0 as c_uint),
2356 llvm::LLVMGetParam(llfn, 1 as c_uint),
2364 let result = llvm::LLVMBuildCall(bld,
2367 args.len() as c_uint,
2369 llvm::LLVMBuildRet(bld, result);
2374 pub fn fill_fn_pair(bcx: block, pair: ValueRef, llfn: ValueRef,
2375 llenvptr: ValueRef) {
2376 let ccx = bcx.ccx();
2377 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2378 Store(bcx, llfn, code_cell);
2379 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2380 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2381 Store(bcx, llenvblobptr, env_cell);
2384 pub fn item_path(ccx: &CrateContext, i: @ast::item) -> path {
2385 let base = match ccx.tcx.items.get_copy(&i.id) {
2386 ast_map::node_item(_, p) => p,
2387 // separate map for paths?
2388 _ => fail!("item_path")
2390 vec::append(/*bad*/copy *base, [path_name(i.ident)])
2393 pub fn get_item_val(ccx: @mut CrateContext, id: ast::node_id) -> ValueRef {
2394 debug!("get_item_val(id=`%?`)", id);
2395 let val = ccx.item_vals.find_copy(&id);
2399 let mut exprt = false;
2400 let item = ccx.tcx.items.get_copy(&id);
2401 let val = match item {
2402 ast_map::node_item(i, pth) => {
2403 let my_path = vec::append(/*bad*/copy *pth,
2404 [path_name(i.ident)]);
2406 ast::item_static(_, m, expr) => {
2407 let typ = ty::node_id_to_type(ccx.tcx, i.id);
2408 let s = mangle_exported_name(ccx, my_path, typ);
2409 // We need the translated value here, because for enums the
2410 // LLVM type is not fully determined by the Rust type.
2411 let v = consts::const_expr(ccx, expr);
2412 ccx.const_values.insert(id, v);
2413 exprt = m == ast::m_mutbl;
2415 let llty = llvm::LLVMTypeOf(v);
2416 let g = str::as_c_str(s, |buf| {
2417 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2419 ccx.item_symbols.insert(i.id, s);
2423 ast::item_fn(_, purity, _, _, _) => {
2424 let llfn = if purity != ast::extern_fn {
2425 register_fn(ccx, i.span, my_path, i.id, i.attrs)
2427 foreign::register_foreign_fn(ccx,
2433 set_inline_hint_if_appr(i.attrs, llfn);
2436 _ => fail!("get_item_val: weird result in table")
2439 ast_map::node_trait_method(trait_method, _, pth) => {
2440 debug!("get_item_val(): processing a node_trait_method");
2441 match *trait_method {
2442 ast::required(_) => {
2443 ccx.sess.bug("unexpected variant: required trait method in \
2446 ast::provided(m) => {
2448 register_method(ccx, id, pth, m)
2452 ast_map::node_method(m, _, pth) => {
2454 register_method(ccx, id, pth, m)
2456 ast_map::node_foreign_item(ni, _, _, pth) => {
2459 ast::foreign_item_fn(*) => {
2460 register_fn(ccx, ni.span,
2461 vec::append(/*bad*/copy *pth,
2462 [path_name(ni.ident)]),
2466 ast::foreign_item_static(*) => {
2467 let typ = ty::node_id_to_type(ccx.tcx, ni.id);
2468 let ident = token::ident_to_str(&ni.ident);
2469 let g = do str::as_c_str(ident) |buf| {
2471 let ty = type_of(ccx, typ);
2472 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2480 ast_map::node_variant(ref v, enm, pth) => {
2483 ast::tuple_variant_kind(ref args) => {
2484 assert!(args.len() != 0u);
2485 let pth = vec::append(/*bad*/copy *pth,
2486 [path_name(enm.ident),
2487 path_name((*v).node.name)]);
2488 llfn = match enm.node {
2489 ast::item_enum(_, _) => {
2490 register_fn(ccx, (*v).span, pth, id, enm.attrs)
2492 _ => fail!("node_variant, shouldn't happen")
2495 ast::struct_variant_kind(_) => {
2496 fail!("struct variant kind unexpected in get_item_val")
2499 set_inline_hint(llfn);
2503 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2504 // Only register the constructor if this is a tuple-like struct.
2505 match struct_def.ctor_id {
2507 ccx.tcx.sess.bug("attempt to register a constructor of \
2508 a non-tuple-like struct")
2511 let llfn = register_fn(ccx,
2513 /*bad*/copy *struct_path,
2516 set_inline_hint(llfn);
2523 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2527 if !(exprt || ccx.reachable.contains(&id)) {
2528 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2530 ccx.item_vals.insert(id, val);
2536 pub fn register_method(ccx: @mut CrateContext,
2538 pth: @ast_map::path,
2539 m: @ast::method) -> ValueRef {
2540 let mty = ty::node_id_to_type(ccx.tcx, id);
2541 let pth = vec::append(/*bad*/copy *pth, [path_name((ccx.names)("meth")),
2542 path_name(m.ident)]);
2543 let llfn = register_fn_full(ccx, m.span, pth, id, m.attrs, mty);
2544 set_inline_hint_if_appr(m.attrs, llfn);
2548 // The constant translation pass.
2549 pub fn trans_constant(ccx: @mut CrateContext, it: @ast::item) {
2550 let _icx = push_ctxt("trans_constant");
2552 ast::item_enum(ref enum_definition, _) => {
2553 let vi = ty::enum_variants(ccx.tcx,
2554 ast::def_id { crate: ast::local_crate,
2557 let path = item_path(ccx, it);
2558 for (*enum_definition).variants.iter().advance |variant| {
2559 let p = vec::append(/*bad*/copy path, [
2560 path_name(variant.node.name),
2561 path_name(special_idents::descrim)
2563 let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2564 let disr_val = vi[i].disr_val;
2565 note_unique_llvm_symbol(ccx, s);
2566 let discrim_gvar = str::as_c_str(s, |buf| {
2568 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2572 llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, disr_val));
2573 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2575 ccx.discrims.insert(
2576 local_def(variant.node.id), discrim_gvar);
2577 ccx.discrim_symbols.insert(variant.node.id, s);
2585 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::crate) {
2588 visit::mk_simple_visitor(@visit::SimpleVisitor {
2589 visit_item: |a| trans_constant(ccx, a),
2590 ..*visit::default_simple_visitor()
2594 pub fn vp2i(cx: block, v: ValueRef) -> ValueRef {
2596 return PtrToInt(cx, v, ccx.int_type);
2599 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2601 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2606 ($name:expr, $args:expr, $ret:expr) => ({
2608 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2609 intrinsics.insert(name, f);
2613 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2614 let i8p = Type::i8p();
2615 let mut intrinsics = HashMap::new();
2617 ifn!("llvm.memcpy.p0i8.p0i8.i32",
2618 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2619 ifn!("llvm.memcpy.p0i8.p0i8.i64",
2620 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2621 ifn!("llvm.memmove.p0i8.p0i8.i32",
2622 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2623 ifn!("llvm.memmove.p0i8.p0i8.i64",
2624 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2625 ifn!("llvm.memset.p0i8.i32",
2626 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2627 ifn!("llvm.memset.p0i8.i64",
2628 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2630 ifn!("llvm.trap", [], Type::void());
2631 ifn!("llvm.frameaddress", [Type::i32()], i8p);
2633 ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2634 ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2635 ifn!("llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2636 ifn!("llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2638 ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2639 ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2640 ifn!("llvm.sin.f32", [Type::f32()], Type::f32());
2641 ifn!("llvm.sin.f64", [Type::f64()], Type::f64());
2642 ifn!("llvm.cos.f32", [Type::f32()], Type::f32());
2643 ifn!("llvm.cos.f64", [Type::f64()], Type::f64());
2644 ifn!("llvm.exp.f32", [Type::f32()], Type::f32());
2645 ifn!("llvm.exp.f64", [Type::f64()], Type::f64());
2646 ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2647 ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2648 ifn!("llvm.log.f32", [Type::f32()], Type::f32());
2649 ifn!("llvm.log.f64", [Type::f64()], Type::f64());
2650 ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2651 ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2652 ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2653 ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2655 ifn!("llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2656 ifn!("llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2658 ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2659 ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2660 ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2661 ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2662 ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2663 ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2664 ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2665 ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2667 ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2668 ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2669 ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2670 ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2672 ifn!("llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2673 ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2674 ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2675 ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2677 ifn!("llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2678 ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2679 ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2680 ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2682 ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2683 ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2684 ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2689 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2690 ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2691 ifn!("llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2694 pub fn trap(bcx: block) {
2695 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2696 Some(&x) => { Call(bcx, x, []); },
2697 _ => bcx.sess().bug("unbound llvm.trap in trap")
2701 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2702 if !ccx.sess.opts.gc || !ccx.uses_gc {
2706 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2707 let gc_metadata = do str::as_c_str(gc_metadata_name) |buf| {
2709 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2713 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2714 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2715 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2719 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2720 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2721 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2722 let map = do "_rust_mod_map".as_c_str |buf| {
2724 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2727 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2728 let mut elts: ~[ValueRef] = ~[];
2730 // This is not ideal, but the borrow checker doesn't
2731 // like the multiple borrows. At least, it doesn't
2732 // like them on the current snapshot. (2013-06-14)
2734 for ccx.module_data.each_key |k| {
2735 keys.push(k.to_managed());
2738 for keys.iter().advance |key| {
2739 let val = *ccx.module_data.find_equiv(key).get();
2740 let s_const = C_cstr(ccx, *key);
2741 let s_ptr = p2i(ccx, s_const);
2742 let v_ptr = p2i(ccx, val);
2743 let elt = C_struct([s_ptr, v_ptr]);
2746 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2749 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2755 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2756 llmod: ModuleRef) -> ValueRef {
2757 let targ_cfg = sess.targ_cfg;
2758 let int_type = Type::int(targ_cfg.arch);
2759 let mut n_subcrates = 1;
2760 let cstore = sess.cstore;
2761 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2762 let mapname = if *sess.building_library {
2763 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2767 let sym_name = ~"_rust_crate_map_" + mapname;
2768 let arrtype = Type::array(&int_type, n_subcrates as u64);
2769 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2770 let map = str::as_c_str(sym_name, |buf| {
2772 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2775 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2779 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2780 let mut subcrates: ~[ValueRef] = ~[];
2782 let cstore = ccx.sess.cstore;
2783 while cstore::have_crate_data(cstore, i) {
2784 let cdata = cstore::get_crate_data(cstore, i);
2785 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2787 cstore::get_crate_vers(cstore, i),
2788 cstore::get_crate_hash(cstore, i));
2789 let cr = str::as_c_str(nm, |buf| {
2791 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2794 subcrates.push(p2i(ccx, cr));
2797 subcrates.push(C_int(ccx, 0));
2800 let annihilate_def_id = ccx.tcx.lang_items.annihilate_fn();
2801 if annihilate_def_id.crate == ast::local_crate {
2802 llannihilatefn = get_item_val(ccx, annihilate_def_id.node);
2804 let annihilate_fn_type = csearch::get_type(ccx.tcx,
2805 annihilate_def_id).ty;
2806 llannihilatefn = trans_external_path(ccx,
2808 annihilate_fn_type);
2812 let mod_map = create_module_map(ccx);
2813 llvm::LLVMSetInitializer(map, C_struct(
2815 lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2817 C_array(ccx.int_type, subcrates)]));
2821 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2822 -> encoder::EncodeParams<'r> {
2824 let diag = cx.sess.diagnostic();
2825 let item_symbols = &cx.item_symbols;
2826 let discrim_symbols = &cx.discrim_symbols;
2827 let link_meta = &cx.link_meta;
2828 encoder::EncodeParams {
2831 reachable: cx.reachable,
2832 reexports2: cx.exp_map2,
2833 item_symbols: item_symbols,
2834 discrim_symbols: discrim_symbols,
2835 link_meta: link_meta,
2836 cstore: cx.sess.cstore,
2837 encode_inlined_item: ie
2841 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::crate) {
2842 if !*cx.sess.building_library { return; }
2844 let encode_inlined_item: encoder::encode_inlined_item =
2845 |ecx, ebml_w, path, ii|
2846 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2848 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2849 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2850 let llconst = C_struct([llmeta]);
2851 let mut llglobal = str::as_c_str("rust_metadata", |buf| {
2853 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2857 llvm::LLVMSetInitializer(llglobal, llconst);
2858 str::as_c_str(cx.sess.targ_cfg.target_strs.meta_sect_name, |buf| {
2859 llvm::LLVMSetSection(llglobal, buf)
2861 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2863 let t_ptr_i8 = Type::i8p();
2864 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2865 let llvm_used = do "llvm.used".as_c_str |buf| {
2866 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2868 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2869 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2873 // Writes the current ABI version into the crate.
2874 pub fn write_abi_version(ccx: &mut CrateContext) {
2875 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
2878 pub fn trans_crate(sess: session::Session,
2882 emap2: resolve::ExportMap2,
2883 maps: astencode::Maps) -> (ContextRef, ModuleRef, LinkMeta) {
2885 let mut symbol_hasher = hash::default_state();
2886 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
2887 let reachable = reachable::find_reachable(
2894 // Append ".rc" to crate name as LLVM module identifier.
2896 // LLVM code generator emits a ".file filename" directive
2897 // for ELF backends. Value of the "filename" is set as the
2898 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2899 // crashes if the module identifer is same as other symbols
2900 // such as a function name in the module.
2901 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2902 let llmod_id = link_meta.name.to_owned() + ".rc";
2904 // FIXME(#6511): get LLVM building with --enable-threads so this
2905 // function can be called
2906 // if !llvm::LLVMRustStartMultithreading() {
2907 // sess.bug("couldn't enable multi-threaded LLVM");
2910 let ccx = @mut CrateContext::new(sess, llmod_id, tcx, emap2, maps,
2911 symbol_hasher, link_meta, reachable);
2913 let _icx = push_ctxt("data");
2914 trans_constants(ccx, crate);
2918 let _icx = push_ctxt("text");
2919 trans_mod(ccx, &crate.node.module);
2922 decl_gc_metadata(ccx, llmod_id);
2923 fill_crate_map(ccx, ccx.crate_map);
2924 glue::emit_tydescs(ccx);
2925 write_abi_version(ccx);
2926 if ccx.sess.opts.debuginfo {
2927 debuginfo::finalize(ccx);
2930 // Translate the metadata.
2931 write_metadata(ccx, crate);
2932 if ccx.sess.trans_stats() {
2933 io::println("--- trans stats ---");
2934 io::println(fmt!("n_static_tydescs: %u",
2935 ccx.stats.n_static_tydescs));
2936 io::println(fmt!("n_glues_created: %u",
2937 ccx.stats.n_glues_created));
2938 io::println(fmt!("n_null_glues: %u", ccx.stats.n_null_glues));
2939 io::println(fmt!("n_real_glues: %u", ccx.stats.n_real_glues));
2941 io::println(fmt!("n_fns: %u", ccx.stats.n_fns));
2942 io::println(fmt!("n_monos: %u", ccx.stats.n_monos));
2943 io::println(fmt!("n_inlines: %u", ccx.stats.n_inlines));
2944 io::println(fmt!("n_closures: %u", ccx.stats.n_closures));
2947 if ccx.sess.count_llvm_insns() {
2948 for ccx.stats.llvm_insns.each |&k, &v| {
2949 io::println(fmt!("%-7u %s", v, k));
2953 let llcx = ccx.llcx;
2954 let link_meta = ccx.link_meta;
2955 let llmod = ccx.llmod;
2957 return (llcx, llmod, link_meta);