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::callee;
45 use middle::trans::common::*;
46 use middle::trans::consts;
47 use middle::trans::controlflow;
48 use middle::trans::datum;
49 use middle::trans::debuginfo;
50 use middle::trans::expr;
51 use middle::trans::foreign;
52 use middle::trans::glue;
53 use middle::trans::inline;
54 use middle::trans::machine;
55 use middle::trans::machine::{llalign_of_min, llsize_of};
56 use middle::trans::meth;
57 use middle::trans::monomorphize;
58 use middle::trans::tvec;
59 use middle::trans::type_of;
60 use middle::trans::type_of::*;
62 use util::common::indenter;
63 use util::ppaux::{Repr, ty_to_str};
65 use middle::trans::type_::Type;
68 use std::hashmap::{HashMap, HashSet};
71 use std::libc::c_uint;
78 use syntax::ast::ident;
79 use syntax::ast_map::{path, path_elt_to_str, path_name};
80 use syntax::ast_util::{local_def};
82 use syntax::attr::AttrMetaMethods;
83 use syntax::codemap::span;
84 use syntax::parse::token;
85 use syntax::parse::token::{special_idents};
86 use syntax::print::pprust::stmt_to_str;
88 use syntax::{ast, ast_util, codemap, ast_map};
89 use syntax::abi::{X86, X86_64, Arm, Mips};
91 pub use middle::trans::context::task_llcx;
93 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
95 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
96 let opt = local_data::get(task_local_insn_key, |k| k.map(|&k| *k));
102 pub fn init_insn_ctxt() {
103 local_data::set(task_local_insn_key, @~[]);
106 pub struct _InsnCtxt { _x: () }
109 impl Drop for _InsnCtxt {
111 do local_data::modify(task_local_insn_key) |c| {
112 do c.map_consume |ctx| {
113 let mut ctx = (*ctx).clone();
121 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
122 debug!("new InsnCtxt: %s", s);
123 do local_data::modify(task_local_insn_key) |c| {
124 do c.map_consume |ctx| {
125 let mut ctx = (*ctx).clone();
133 fn fcx_has_nonzero_span(fcx: fn_ctxt) -> bool {
136 Some(span) => *span.lo != 0 || *span.hi != 0
140 struct StatRecorder<'self> {
141 ccx: @mut CrateContext,
147 impl<'self> StatRecorder<'self> {
148 pub fn new(ccx: @mut CrateContext,
149 name: &'self str) -> StatRecorder<'self> {
150 let start = if ccx.sess.trans_stats() {
151 time::precise_time_ns()
155 let istart = ccx.stats.n_llvm_insns;
166 impl<'self> Drop for StatRecorder<'self> {
168 if self.ccx.sess.trans_stats() {
169 let end = time::precise_time_ns();
170 let elapsed = ((end - self.start) / 1_000_000) as uint;
171 let iend = self.ccx.stats.n_llvm_insns;
172 self.ccx.stats.fn_stats.push((self.name.to_owned(),
174 iend - self.istart));
175 self.ccx.stats.n_fns += 1;
176 // Reset LLVM insn count to avoid compound costs.
177 self.ccx.stats.n_llvm_insns = self.istart;
182 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
183 let llfn: ValueRef = do name.as_c_str |buf| {
185 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
189 lib::llvm::SetFunctionCallConv(llfn, cc);
193 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
194 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
197 // Only use this if you are going to actually define the function. It's
198 // not valid to simply declare a function as internal.
199 pub fn decl_internal_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
200 let llfn = decl_cdecl_fn(llmod, name, ty);
201 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
205 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: @str,
206 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
207 match externs.find_copy(&name) {
211 let f = decl_fn(llmod, name, cc, ty);
212 externs.insert(name, f);
216 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
217 name: @str, ty: Type) -> ValueRef {
218 match externs.find_copy(&name) {
223 let c = do name.as_c_str |buf| {
224 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
226 externs.insert(name, c);
230 pub fn umax(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
231 let _icx = push_ctxt("umax");
232 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
233 return Select(cx, cond, b, a);
236 pub fn umin(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
237 let _icx = push_ctxt("umin");
238 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
239 return Select(cx, cond, a, b);
242 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
243 // The type of the returned pointer is always i8*. If you care about the
244 // return type, use bump_ptr().
245 pub fn ptr_offs(bcx: block, base: ValueRef, sz: ValueRef) -> ValueRef {
246 let _icx = push_ctxt("ptr_offs");
247 let raw = PointerCast(bcx, base, Type::i8p());
248 InBoundsGEP(bcx, raw, [sz])
251 // Increment a pointer by a given amount and then cast it to be a pointer
253 pub fn bump_ptr(bcx: block, t: ty::t, base: ValueRef, sz: ValueRef) ->
255 let _icx = push_ctxt("bump_ptr");
257 let bumped = ptr_offs(bcx, base, sz);
258 let typ = type_of(ccx, t).ptr_to();
259 PointerCast(bcx, bumped, typ)
262 // Returns a pointer to the body for the box. The box may be an opaque
263 // box. The result will be casted to the type of body_t, if it is statically
266 // The runtime equivalent is box_body() in "rust_internal.h".
267 pub fn opaque_box_body(bcx: block,
269 boxptr: ValueRef) -> ValueRef {
270 let _icx = push_ctxt("opaque_box_body");
272 let ty = type_of(ccx, body_t);
273 let ty = Type::box(ccx, &ty);
274 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
275 GEPi(bcx, boxptr, [0u, abi::box_field_body])
278 // malloc_raw_dyn: allocates a box to contain a given type, but with a
279 // potentially dynamic size.
280 pub fn malloc_raw_dyn(bcx: block,
283 size: ValueRef) -> Result {
284 let _icx = push_ctxt("malloc_raw");
287 fn require_alloc_fn(bcx: block, t: ty::t, it: LangItem) -> ast::def_id {
288 let li = &bcx.tcx().lang_items;
289 match li.require(it) {
292 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
293 bcx.ty_to_str(t), s));
298 if heap == heap_exchange {
299 let llty_value = type_of::type_of(ccx, t);
303 let r = callee::trans_lang_call(
305 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
308 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
310 // we treat ~fn, @fn and @[] as @ here, which isn't ideal
311 let (mk_fn, langcall) = match heap {
312 heap_managed | heap_managed_unique => {
314 require_alloc_fn(bcx, t, MallocFnLangItem))
316 heap_exchange_closure => {
318 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
320 _ => fail!("heap_exchange already handled")
323 // Grab the TypeRef type of box_ptr_ty.
324 let box_ptr_ty = mk_fn(bcx.tcx(), t);
325 let llty = type_of(ccx, box_ptr_ty);
327 // Get the tydesc for the body:
328 let static_ti = get_tydesc(ccx, t);
329 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
332 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
333 let r = callee::trans_lang_call(
338 let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
339 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
344 // malloc_raw: expects an unboxed type and returns a pointer to
345 // enough space for a box of that type. This includes a rust_opaque_box
347 pub fn malloc_raw(bcx: block, t: ty::t, heap: heap) -> Result {
348 let ty = type_of(bcx.ccx(), t);
349 let size = llsize_of(bcx.ccx(), ty);
350 malloc_raw_dyn(bcx, t, heap, size)
353 pub struct MallocResult {
359 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
360 // and pulls out the body
361 pub fn malloc_general_dyn(bcx: block, t: ty::t, heap: heap, size: ValueRef)
363 assert!(heap != heap_exchange);
364 let _icx = push_ctxt("malloc_general");
365 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
366 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
368 MallocResult { bcx: bcx, box: llbox, body: body }
371 pub fn malloc_general(bcx: block, t: ty::t, heap: heap) -> MallocResult {
372 let ty = type_of(bcx.ccx(), t);
373 assert!(heap != heap_exchange);
374 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
376 pub fn malloc_boxed(bcx: block, t: ty::t)
378 malloc_general(bcx, t, heap_managed)
381 pub fn heap_for_unique(bcx: block, t: ty::t) -> heap {
382 if ty::type_contents(bcx.tcx(), t).contains_managed() {
389 pub fn maybe_set_managed_unique_rc(bcx: block, bx: ValueRef, heap: heap) {
390 assert!(heap != heap_exchange);
391 if heap == heap_managed_unique {
392 // In cases where we are looking at a unique-typed allocation in the
393 // managed heap (thus have refcount 1 from the managed allocator),
394 // such as a ~(@foo) or such. These need to have their refcount forced
395 // to -2 so the annihilator ignores them.
396 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
397 let rc_val = C_int(bcx.ccx(), -2);
398 Store(bcx, rc_val, rc);
402 // Type descriptor and type glue stuff
404 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
405 get_tydesc(ccx, t).tydesc
408 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
409 match ccx.tydescs.find(&t) {
416 ccx.stats.n_static_tydescs += 1u;
417 let inf = glue::declare_tydesc(ccx, t);
418 ccx.tydescs.insert(t, inf);
422 pub fn set_optimize_for_size(f: ValueRef) {
424 llvm::LLVMAddFunctionAttr(f,
425 lib::llvm::OptimizeForSizeAttribute
431 pub fn set_no_inline(f: ValueRef) {
433 llvm::LLVMAddFunctionAttr(f,
434 lib::llvm::NoInlineAttribute as c_uint,
439 pub fn set_no_unwind(f: ValueRef) {
441 llvm::LLVMAddFunctionAttr(f,
442 lib::llvm::NoUnwindAttribute as c_uint,
447 // Tell LLVM to emit the information necessary to unwind the stack for the
449 pub fn set_uwtable(f: ValueRef) {
451 llvm::LLVMAddFunctionAttr(f,
452 lib::llvm::UWTableAttribute as c_uint,
457 pub fn set_inline_hint(f: ValueRef) {
459 llvm::LLVMAddFunctionAttr(f,
460 lib::llvm::InlineHintAttribute as c_uint,
465 pub fn set_inline_hint_if_appr(attrs: &[ast::Attribute],
468 match find_inline_attr(attrs) {
469 InlineHint => set_inline_hint(llfn),
470 InlineAlways => set_always_inline(llfn),
471 InlineNever => set_no_inline(llfn),
472 InlineNone => { /* fallthrough */ }
476 pub fn set_always_inline(f: ValueRef) {
478 llvm::LLVMAddFunctionAttr(f,
479 lib::llvm::AlwaysInlineAttribute as c_uint,
484 pub fn set_fixed_stack_segment(f: ValueRef) {
486 llvm::LLVMAddFunctionAttr(f, 0, 1 << (39 - 32));
490 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
491 if ty::type_is_structural(t) {
492 set_optimize_for_size(f);
493 } else { set_always_inline(f); }
496 // Double-check that we never ask LLVM to declare the same symbol twice. It
497 // silently mangles such symbols, breaking our linkage model.
498 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
499 if ccx.all_llvm_symbols.contains(&sym) {
500 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
502 ccx.all_llvm_symbols.insert(sym);
506 pub fn get_res_dtor(ccx: @mut CrateContext,
508 parent_id: ast::def_id,
511 let _icx = push_ctxt("trans_res_dtor");
512 if !substs.is_empty() {
513 let did = if did.crate != ast::local_crate {
514 inline::maybe_instantiate_inline(ccx, did)
518 assert_eq!(did.crate, ast::local_crate);
519 let tsubsts = ty::substs { self_r: None, self_ty: None,
520 tps: /*bad*/ substs.to_owned() };
521 let (val, _) = monomorphize::monomorphic_fn(ccx,
529 } else if did.crate == ast::local_crate {
530 get_item_val(ccx, did.node)
533 let name = csearch::get_symbol(ccx.sess.cstore, did);
534 let class_ty = ty::subst_tps(tcx,
537 ty::lookup_item_type(tcx, parent_id).ty);
538 let llty = type_of_dtor(ccx, class_ty);
539 let name = name.to_managed(); // :-(
540 get_extern_fn(&mut ccx.externs,
543 lib::llvm::CCallConv,
548 // Structural comparison: a rather involved form of glue.
549 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
550 if cx.sess.opts.save_temps {
551 let _: () = str::as_c_str(s, |buf| {
553 llvm::LLVMSetValueName(v, buf)
560 // Used only for creating scalar comparison glue.
561 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
563 // NB: This produces an i1, not a Rust bool (i8).
564 pub fn compare_scalar_types(cx: block,
570 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
572 match ty::get(t).sty {
573 ty::ty_nil => rslt(cx, f(nil_type)),
574 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
575 ty::ty_int(_) => rslt(cx, f(signed_int)),
576 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
577 ty::ty_float(_) => rslt(cx, f(floating_point)),
580 controlflow::trans_fail(
582 @"attempt to compare values of type type"),
586 // Should never get here, because t is scalar.
587 cx.sess().bug("non-scalar type passed to \
588 compare_scalar_types")
594 // A helper function to do the actual comparison of scalar values.
595 pub fn compare_scalar_values(cx: block,
601 let _icx = push_ctxt("compare_scalar_values");
602 fn die(cx: block) -> ! {
603 cx.tcx().sess.bug("compare_scalar_values: must be a\
604 comparison operator");
608 // We don't need to do actual comparisons for nil.
609 // () == () holds but () < () does not.
611 ast::eq | ast::le | ast::ge => return C_i1(true),
612 ast::ne | ast::lt | ast::gt => return C_i1(false),
613 // refinements would be nice
619 ast::eq => lib::llvm::RealOEQ,
620 ast::ne => lib::llvm::RealUNE,
621 ast::lt => lib::llvm::RealOLT,
622 ast::le => lib::llvm::RealOLE,
623 ast::gt => lib::llvm::RealOGT,
624 ast::ge => lib::llvm::RealOGE,
627 return FCmp(cx, cmp, lhs, rhs);
631 ast::eq => lib::llvm::IntEQ,
632 ast::ne => lib::llvm::IntNE,
633 ast::lt => lib::llvm::IntSLT,
634 ast::le => lib::llvm::IntSLE,
635 ast::gt => lib::llvm::IntSGT,
636 ast::ge => lib::llvm::IntSGE,
639 return ICmp(cx, cmp, lhs, rhs);
643 ast::eq => lib::llvm::IntEQ,
644 ast::ne => lib::llvm::IntNE,
645 ast::lt => lib::llvm::IntULT,
646 ast::le => lib::llvm::IntULE,
647 ast::gt => lib::llvm::IntUGT,
648 ast::ge => lib::llvm::IntUGE,
651 return ICmp(cx, cmp, lhs, rhs);
656 pub type val_and_ty_fn<'self> = &'self fn(block, ValueRef, ty::t) -> block;
658 pub fn load_inbounds(cx: block, p: ValueRef, idxs: &[uint]) -> ValueRef {
659 return Load(cx, GEPi(cx, p, idxs));
662 pub fn store_inbounds(cx: block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
663 Store(cx, v, GEPi(cx, p, idxs));
666 // Iterates through the elements of a structural type.
667 pub fn iter_structural_ty(cx: block, av: ValueRef, t: ty::t,
668 f: val_and_ty_fn) -> block {
669 let _icx = push_ctxt("iter_structural_ty");
671 fn iter_variant(cx: block, repr: &adt::Repr, av: ValueRef,
672 variant: @ty::VariantInfo,
673 tps: &[ty::t], f: val_and_ty_fn) -> block {
674 let _icx = push_ctxt("iter_variant");
678 for variant.args.iter().enumerate().advance |(i, &arg)| {
680 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
681 ty::subst_tps(tcx, tps, None, arg));
687 match ty::get(t).sty {
688 ty::ty_struct(*) => {
689 let repr = adt::represent_type(cx.ccx(), t);
690 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
691 for field_tys.iter().enumerate().advance |(i, field_ty)| {
692 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
693 cx = f(cx, llfld_a, field_ty.mt.ty);
697 ty::ty_estr(ty::vstore_fixed(_)) |
698 ty::ty_evec(_, ty::vstore_fixed(_)) => {
699 let (base, len) = tvec::get_base_and_len(cx, av, t);
700 cx = tvec::iter_vec_raw(cx, base, t, len, f);
702 ty::ty_tup(ref args) => {
703 let repr = adt::represent_type(cx.ccx(), t);
704 for args.iter().enumerate().advance |(i, arg)| {
705 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
706 cx = f(cx, llfld_a, *arg);
709 ty::ty_enum(tid, ref substs) => {
712 let repr = adt::represent_type(ccx, t);
713 let variants = ty::enum_variants(ccx.tcx, tid);
714 let n_variants = (*variants).len();
716 // NB: we must hit the discriminant first so that structural
717 // comparison know not to proceed when the discriminants differ.
719 match adt::trans_switch(cx, repr, av) {
720 (_match::single, None) => {
721 cx = iter_variant(cx, repr, av, variants[0],
724 (_match::switch, Some(lldiscrim_a)) => {
725 cx = f(cx, lldiscrim_a, ty::mk_int());
726 let unr_cx = sub_block(cx, "enum-iter-unr");
728 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
730 let next_cx = sub_block(cx, "enum-iter-next");
732 for (*variants).iter().advance |variant| {
734 sub_block(cx, ~"enum-iter-variant-" +
735 int::to_str(variant.disr_val));
737 iter_variant(variant_cx, repr, av, *variant,
738 substs.tps, |x,y,z| f(x,y,z));
739 match adt::trans_case(cx, repr, variant.disr_val) {
740 _match::single_result(r) => {
741 AddCase(llswitch, r.val, variant_cx.llbb)
743 _ => ccx.sess.unimpl("value from adt::trans_case \
744 in iter_structural_ty")
746 Br(variant_cx, next_cx.llbb);
750 _ => ccx.sess.unimpl("value from adt::trans_switch \
751 in iter_structural_ty")
754 _ => cx.sess().unimpl("type in iter_structural_ty")
759 pub fn cast_shift_expr_rhs(cx: block, op: ast::binop,
760 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
761 cast_shift_rhs(op, lhs, rhs,
762 |a,b| Trunc(cx, a, b),
763 |a,b| ZExt(cx, a, b))
766 pub fn cast_shift_const_rhs(op: ast::binop,
767 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
768 cast_shift_rhs(op, lhs, rhs,
769 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
770 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
773 pub fn cast_shift_rhs(op: ast::binop,
774 lhs: ValueRef, rhs: ValueRef,
775 trunc: &fn(ValueRef, Type) -> ValueRef,
776 zext: &fn(ValueRef, Type) -> ValueRef)
778 // Shifts may have any size int on the rhs
780 if ast_util::is_shift_binop(op) {
781 let rhs_llty = val_ty(rhs);
782 let lhs_llty = val_ty(lhs);
783 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
784 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
787 } else if lhs_sz > rhs_sz {
788 // FIXME (#1877: If shifting by negative
789 // values becomes not undefined then this is wrong.
800 pub fn fail_if_zero(cx: block, span: span, divrem: ast::binop,
801 rhs: ValueRef, rhs_t: ty::t) -> block {
802 let text = if divrem == ast::div {
803 @"attempted to divide by zero"
805 @"attempted remainder with a divisor of zero"
807 let is_zero = match ty::get(rhs_t).sty {
809 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
810 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
813 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
814 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
817 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
818 ty_to_str(cx.ccx().tcx, rhs_t));
821 do with_cond(cx, is_zero) |bcx| {
822 controlflow::trans_fail(bcx, Some(span), text)
826 pub fn null_env_ptr(bcx: block) -> ValueRef {
827 C_null(Type::opaque_box(bcx.ccx()).ptr_to())
830 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::def_id, t: ty::t)
832 let name = csearch::get_symbol(ccx.sess.cstore, did).to_managed(); // Sad
833 match ty::get(t).sty {
834 ty::ty_bare_fn(_) | ty::ty_closure(_) => {
835 let llty = type_of_fn_from_ty(ccx, t);
836 return get_extern_fn(&mut ccx.externs, ccx.llmod, name,
837 lib::llvm::CCallConv, llty);
840 let llty = type_of(ccx, t);
841 return get_extern_const(&mut ccx.externs, ccx.llmod, name, llty);
846 pub fn invoke(bcx: block, llfn: ValueRef, llargs: ~[ValueRef])
847 -> (ValueRef, block) {
848 let _icx = push_ctxt("invoke_");
850 return (C_null(Type::i8()), bcx);
853 match bcx.node_info {
854 None => debug!("invoke at ???"),
856 debug!("invoke at %s",
857 bcx.sess().codemap.span_to_str(node_info.span));
861 if need_invoke(bcx) {
863 debug!("invoking %x at %x",
864 ::std::cast::transmute(llfn),
865 ::std::cast::transmute(bcx.llbb));
866 for llargs.iter().advance |&llarg| {
867 debug!("arg: %x", ::std::cast::transmute(llarg));
870 let normal_bcx = sub_block(bcx, "normal return");
871 let llresult = Invoke(bcx,
875 get_landing_pad(bcx));
876 return (llresult, normal_bcx);
879 debug!("calling %x at %x",
880 ::std::cast::transmute(llfn),
881 ::std::cast::transmute(bcx.llbb));
882 for llargs.iter().advance |&llarg| {
883 debug!("arg: %x", ::std::cast::transmute(llarg));
886 let llresult = Call(bcx, llfn, llargs);
887 return (llresult, bcx);
891 pub fn need_invoke(bcx: block) -> bool {
892 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
896 // Avoid using invoke if we are already inside a landing pad.
901 if have_cached_lpad(bcx) {
905 // Walk the scopes to look for cleanups
907 let mut cur_scope = cur.scope;
909 cur_scope = match cur_scope {
911 for inf.cleanups.iter().advance |cleanup| {
913 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
914 if cleanup_type == normal_exit_and_unwind {
923 cur = match cur.parent {
933 pub fn have_cached_lpad(bcx: block) -> bool {
935 do in_lpad_scope_cx(bcx) |inf| {
936 match inf.landing_pad {
937 Some(_) => res = true,
944 pub fn in_lpad_scope_cx(bcx: block, f: &fn(si: &mut scope_info)) {
946 let mut cur_scope = bcx.scope;
948 cur_scope = match cur_scope {
950 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
957 bcx = block_parent(bcx);
964 pub fn get_landing_pad(bcx: block) -> BasicBlockRef {
965 let _icx = push_ctxt("get_landing_pad");
967 let mut cached = None;
968 let mut pad_bcx = bcx; // Guaranteed to be set below
969 do in_lpad_scope_cx(bcx) |inf| {
970 // If there is a valid landing pad still around, use it
971 match inf.landing_pad {
972 Some(target) => cached = Some(target),
974 pad_bcx = lpad_block(bcx, "unwind");
975 inf.landing_pad = Some(pad_bcx.llbb);
979 // Can't return from block above
980 match cached { Some(b) => return b, None => () }
981 // The landing pad return type (the type being propagated). Not sure what
982 // this represents but it's determined by the personality function and
983 // this is what the EH proposal example uses.
984 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
985 // The exception handling personality function. This is the C++
986 // personality function __gxx_personality_v0, wrapped in our naming
988 let personality = bcx.ccx().upcalls.rust_personality;
989 // The only landing pad clause will be 'cleanup'
990 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
991 // The landing pad block is a cleanup
992 SetCleanup(pad_bcx, llretval);
994 // Because we may have unwound across a stack boundary, we must call into
995 // the runtime to figure out which stack segment we are on and place the
996 // stack limit back into the TLS.
997 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, []);
999 // We store the retval in a function-central alloca, so that calls to
1000 // Resume can find it.
1001 match bcx.fcx.personality {
1002 Some(addr) => Store(pad_bcx, llretval, addr),
1004 let addr = alloca(pad_bcx, val_ty(llretval), "");
1005 bcx.fcx.personality = Some(addr);
1006 Store(pad_bcx, llretval, addr);
1010 // Unwind all parent scopes, and finish with a Resume instr
1011 cleanup_and_leave(pad_bcx, None, None);
1012 return pad_bcx.llbb;
1015 pub fn find_bcx_for_scope(bcx: block, scope_id: ast::node_id) -> block {
1016 let mut bcx_sid = bcx;
1017 let mut cur_scope = bcx_sid.scope;
1019 cur_scope = match cur_scope {
1021 match inf.node_info {
1022 Some(NodeInfo { id, _ }) if id == scope_id => {
1025 // FIXME(#6268, #6248) hacky cleanup for nested method calls
1026 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1033 bcx_sid = match bcx_sid.parent {
1034 None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1035 Some(bcx_par) => bcx_par
1044 pub fn do_spill(bcx: block, v: ValueRef, t: ty::t) -> ValueRef {
1045 if ty::type_is_bot(t) {
1046 return C_null(Type::i8p());
1048 let llptr = alloc_ty(bcx, t, "");
1049 Store(bcx, v, llptr);
1053 // Since this function does *not* root, it is the caller's responsibility to
1054 // ensure that the referent is pointed to by a root.
1055 pub fn do_spill_noroot(cx: block, v: ValueRef) -> ValueRef {
1056 let llptr = alloca(cx, val_ty(v), "");
1057 Store(cx, v, llptr);
1061 pub fn spill_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
1062 let _icx = push_ctxt("spill_if_immediate");
1063 if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1067 pub fn load_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
1068 let _icx = push_ctxt("load_if_immediate");
1069 if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1073 pub fn trans_trace(bcx: block, sp_opt: Option<span>, trace_str: @str) {
1074 if !bcx.sess().trace() { return; }
1075 let _icx = push_ctxt("trans_trace");
1076 add_comment(bcx, trace_str);
1077 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1078 let (V_filename, V_line) = match sp_opt {
1080 let sess = bcx.sess();
1081 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1082 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1085 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1088 let ccx = bcx.ccx();
1089 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1090 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1091 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1092 Call(bcx, ccx.upcalls.trace, args);
1095 pub fn ignore_lhs(_bcx: block, local: &ast::local) -> bool {
1096 match local.node.pat.node {
1097 ast::pat_wild => true, _ => false
1101 pub fn init_local(bcx: block, local: &ast::local) -> block {
1103 debug!("init_local(bcx=%s, local.id=%?)",
1104 bcx.to_str(), local.node.id);
1105 let _indenter = indenter();
1107 let _icx = push_ctxt("init_local");
1109 if ignore_lhs(bcx, local) {
1110 // Handle let _ = e; just like e;
1111 match local.node.init {
1113 return expr::trans_into(bcx, init, expr::Ignore);
1115 None => { return bcx; }
1119 _match::store_local(bcx, local.node.pat, local.node.init)
1122 pub fn trans_stmt(cx: block, s: &ast::stmt) -> block {
1123 let _icx = push_ctxt("trans_stmt");
1124 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1126 if cx.sess().asm_comments() {
1127 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1131 debuginfo::update_source_pos(cx, s.span);
1134 ast::stmt_expr(e, _) | ast::stmt_semi(e, _) => {
1135 bcx = expr::trans_into(cx, e, expr::Ignore);
1137 ast::stmt_decl(d, _) => {
1139 ast::decl_local(ref local) => {
1140 bcx = init_local(bcx, *local);
1141 if cx.sess().opts.extra_debuginfo
1142 && fcx_has_nonzero_span(bcx.fcx) {
1143 debuginfo::create_local_var_metadata(bcx, *local);
1146 ast::decl_item(i) => trans_item(cx.fcx.ccx, i)
1149 ast::stmt_mac(*) => cx.tcx().sess.bug("unexpanded macro")
1155 // You probably don't want to use this one. See the
1156 // next three functions instead.
1157 pub fn new_block(cx: fn_ctxt, parent: Option<block>, scope: Option<@mut scope_info>,
1158 is_lpad: bool, name: &str, opt_node_info: Option<NodeInfo>)
1162 let llbb = do name.as_c_str |buf| {
1163 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1165 let bcx = mk_block(llbb,
1171 for parent.iter().advance |cx| {
1181 pub fn simple_block_scope(parent: Option<@mut scope_info>,
1182 node_info: Option<NodeInfo>) -> @mut scope_info {
1190 node_info: node_info,
1194 // Use this when you're at the top block of a function or the like.
1195 pub fn top_scope_block(fcx: fn_ctxt, opt_node_info: Option<NodeInfo>)
1197 return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1198 "function top level", opt_node_info);
1201 pub fn scope_block(bcx: block,
1202 opt_node_info: Option<NodeInfo>,
1204 return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1208 pub fn loop_scope_block(bcx: block,
1210 loop_label: Option<ident>,
1212 opt_node_info: Option<NodeInfo>) -> block {
1213 return new_block(bcx.fcx, Some(bcx), Some(@mut scope_info {
1215 loop_break: Some(loop_break),
1216 loop_label: loop_label,
1220 node_info: opt_node_info,
1221 }), bcx.is_lpad, n, opt_node_info);
1224 // Use this when creating a block for the inside of a landing pad.
1225 pub fn lpad_block(bcx: block, n: &str) -> block {
1226 new_block(bcx.fcx, Some(bcx), None, true, n, None)
1229 // Use this when you're making a general CFG BB within a scope.
1230 pub fn sub_block(bcx: block, n: &str) -> block {
1231 new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1234 pub fn raw_block(fcx: fn_ctxt, is_lpad: bool, llbb: BasicBlockRef) -> block {
1235 mk_block(llbb, None, is_lpad, None, fcx)
1239 // trans_block_cleanups: Go through all the cleanups attached to this
1240 // block and execute them.
1242 // When translating a block that introduces new variables during its scope, we
1243 // need to make sure those variables go out of scope when the block ends. We
1244 // do that by running a 'cleanup' function for each variable.
1245 // trans_block_cleanups runs all the cleanup functions for the block.
1246 pub fn trans_block_cleanups(bcx: block, cleanups: ~[cleanup]) -> block {
1247 trans_block_cleanups_(bcx, cleanups, false)
1250 pub fn trans_block_cleanups_(bcx: block,
1251 cleanups: &[cleanup],
1252 /* cleanup_cx: block, */
1253 is_lpad: bool) -> block {
1254 let _icx = push_ctxt("trans_block_cleanups");
1255 // NB: Don't short-circuit even if this block is unreachable because
1256 // GC-based cleanup needs to the see that the roots are live.
1258 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1259 if bcx.unreachable && !no_lpads { return bcx; }
1261 for cleanups.rev_iter().advance |cu| {
1263 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1264 // Some types don't need to be cleaned up during
1265 // landing pads because they can be freed en mass later
1266 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1275 // In the last argument, Some(block) mean jump to this block, and none means
1276 // this is a landing pad and leaving should be accomplished with a resume
1278 pub fn cleanup_and_leave(bcx: block,
1279 upto: Option<BasicBlockRef>,
1280 leave: Option<BasicBlockRef>) {
1281 let _icx = push_ctxt("cleanup_and_leave");
1284 let is_lpad = leave == None;
1286 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1288 if bcx.sess().trace() {
1291 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1294 let mut cur_scope = cur.scope;
1296 cur_scope = match cur_scope {
1297 Some (inf) if !inf.empty_cleanups() => {
1298 let (sub_cx, dest, inf_cleanups) = {
1299 let inf = &mut *inf;
1301 let mut dest = None;
1303 let r = (*inf).cleanup_paths.rev_iter().find_(|cp| cp.target == leave);
1304 for r.iter().advance |cp| {
1305 if cp.size == inf.cleanups.len() {
1311 dest = Some(cp.dest);
1314 let sub_cx = sub_block(bcx, "cleanup");
1315 Br(bcx, sub_cx.llbb);
1316 inf.cleanup_paths.push(cleanup_path {
1318 size: inf.cleanups.len(),
1321 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1323 bcx = trans_block_cleanups_(sub_cx,
1326 for dest.iter().advance |&dest| {
1332 Some(inf) => inf.parent,
1338 Some(bb) => { if cur.llbb == bb { break; } }
1341 cur = match cur.parent {
1343 None => { assert!(upto.is_none()); break; }
1347 Some(target) => Br(bcx, target),
1348 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.get())); }
1352 pub fn cleanup_block(bcx: block, upto: Option<BasicBlockRef>) -> block{
1353 let _icx = push_ctxt("cleanup_block");
1357 debug!("cleanup_block: %s", cur.to_str());
1359 if bcx.sess().trace() {
1362 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1365 let mut cur_scope = cur.scope;
1367 cur_scope = match cur_scope {
1369 bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1377 Some(bb) => { if cur.llbb == bb { break; } }
1380 cur = match cur.parent {
1382 None => { assert!(upto.is_none()); break; }
1388 pub fn cleanup_and_Br(bcx: block, upto: block, target: BasicBlockRef) {
1389 let _icx = push_ctxt("cleanup_and_Br");
1390 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1393 pub fn leave_block(bcx: block, out_of: block) -> block {
1394 let _icx = push_ctxt("leave_block");
1395 let next_cx = sub_block(block_parent(out_of), "next");
1396 if bcx.unreachable { Unreachable(next_cx); }
1397 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1401 pub fn with_scope(bcx: block,
1402 opt_node_info: Option<NodeInfo>,
1404 f: &fn(block) -> block) -> block {
1405 let _icx = push_ctxt("with_scope");
1407 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1408 bcx.to_str(), opt_node_info, name);
1409 let _indenter = indenter();
1411 let scope = simple_block_scope(bcx.scope, opt_node_info);
1412 bcx.scope = Some(scope);
1414 let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1415 bcx.scope = scope.parent;
1419 pub fn with_scope_result(bcx: block,
1420 opt_node_info: Option<NodeInfo>,
1422 f: &fn(block) -> Result) -> Result {
1423 let _icx = push_ctxt("with_scope_result");
1425 let scope = simple_block_scope(bcx.scope, opt_node_info);
1426 bcx.scope = Some(scope);
1427 let Result { bcx: out_bcx, val } = f(bcx);
1428 let out_bcx = trans_block_cleanups_(out_bcx,
1429 (scope.cleanups).clone(),
1431 bcx.scope = scope.parent;
1436 pub fn with_scope_datumblock(bcx: block, opt_node_info: Option<NodeInfo>,
1437 name: &str, f: &fn(block) -> datum::DatumBlock)
1438 -> datum::DatumBlock {
1439 use middle::trans::datum::DatumBlock;
1441 let _icx = push_ctxt("with_scope_result");
1442 let scope_cx = scope_block(bcx, opt_node_info, name);
1443 Br(bcx, scope_cx.llbb);
1444 let DatumBlock {bcx, datum} = f(scope_cx);
1445 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1448 pub fn block_locals(b: &ast::blk, it: &fn(@ast::local)) {
1449 for b.stmts.iter().advance |s| {
1451 ast::stmt_decl(d, _) => {
1453 ast::decl_local(ref local) => it(*local),
1454 _ => {} /* fall through */
1457 _ => {} /* fall through */
1462 pub fn with_cond(bcx: block, val: ValueRef, f: &fn(block) -> block) -> block {
1463 let _icx = push_ctxt("with_cond");
1464 let next_cx = base::sub_block(bcx, "next");
1465 let cond_cx = base::sub_block(bcx, "cond");
1466 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1467 let after_cx = f(cond_cx);
1468 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1472 pub fn call_memcpy(cx: block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1473 let _icx = push_ctxt("call_memcpy");
1475 let key = match ccx.sess.targ_cfg.arch {
1476 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1477 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1479 let memcpy = ccx.intrinsics.get_copy(&key);
1480 let src_ptr = PointerCast(cx, src, Type::i8p());
1481 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1482 let size = IntCast(cx, n_bytes, ccx.int_type);
1483 let align = C_i32(align as i32);
1484 let volatile = C_i1(false);
1485 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile]);
1488 pub fn memcpy_ty(bcx: block, dst: ValueRef, src: ValueRef, t: ty::t) {
1489 let _icx = push_ctxt("memcpy_ty");
1490 let ccx = bcx.ccx();
1491 if ty::type_is_structural(t) {
1492 let llty = type_of::type_of(ccx, t);
1493 let llsz = llsize_of(ccx, llty);
1494 let llalign = llalign_of_min(ccx, llty);
1495 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1497 Store(bcx, Load(bcx, src), dst);
1501 pub fn zero_mem(cx: block, llptr: ValueRef, t: ty::t) {
1502 let _icx = push_ctxt("zero_mem");
1505 let llty = type_of::type_of(ccx, t);
1506 memzero(bcx, llptr, llty);
1509 // Always use this function instead of storing a zero constant to the memory
1510 // in question. If you store a zero constant, LLVM will drown in vreg
1511 // allocation for large data structures, and the generated code will be
1512 // awful. (A telltale sign of this is large quantities of
1513 // `mov [byte ptr foo],0` in the generated code.)
1514 pub fn memzero(cx: block, llptr: ValueRef, ty: Type) {
1515 let _icx = push_ctxt("memzero");
1518 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1519 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1520 X86_64 => "llvm.memset.p0i8.i64"
1523 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1524 let llptr = PointerCast(cx, llptr, Type::i8().ptr_to());
1525 let llzeroval = C_u8(0);
1526 let size = IntCast(cx, machine::llsize_of(ccx, ty), ccx.int_type);
1527 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1528 let volatile = C_i1(false);
1529 Call(cx, llintrinsicfn, [llptr, llzeroval, size, align, volatile]);
1532 pub fn alloc_ty(bcx: block, t: ty::t, name: &str) -> ValueRef {
1533 let _icx = push_ctxt("alloc_ty");
1534 let ccx = bcx.ccx();
1535 let ty = type_of::type_of(ccx, t);
1536 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1537 let val = alloca(bcx, ty, name);
1541 pub fn alloca(cx: block, ty: Type, name: &str) -> ValueRef {
1542 alloca_maybe_zeroed(cx, ty, name, false)
1545 pub fn alloca_maybe_zeroed(cx: block, ty: Type, name: &str, zero: bool) -> ValueRef {
1546 let _icx = push_ctxt("alloca");
1549 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1552 let initcx = base::raw_block(cx.fcx, false, cx.fcx.get_llstaticallocas());
1553 let p = Alloca(initcx, ty, name);
1554 if zero { memzero(initcx, p, ty); }
1558 pub fn arrayalloca(cx: block, ty: Type, v: ValueRef) -> ValueRef {
1559 let _icx = push_ctxt("arrayalloca");
1562 return llvm::LLVMGetUndef(ty.to_ref());
1565 return ArrayAlloca(base::raw_block(cx.fcx, false, cx.fcx.get_llstaticallocas()), ty, v);
1568 pub struct BasicBlocks {
1572 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1574 let cx = task_llcx();
1575 str::as_c_str("static_allocas",
1576 |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf))
1580 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1582 let cx = task_llcx();
1583 str::as_c_str("return",
1584 |buf| llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf))
1588 // Creates and returns space for, or returns the argument representing, the
1589 // slot where the return value of the function must go.
1590 pub fn make_return_pointer(fcx: fn_ctxt, output_type: ty::t) -> ValueRef {
1592 if !ty::type_is_immediate(fcx.ccx.tcx, output_type) {
1593 llvm::LLVMGetParam(fcx.llfn, 0)
1595 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1596 alloca(raw_block(fcx, false, fcx.get_llstaticallocas()), lloutputtype,
1597 "__make_return_pointer")
1602 // NB: must keep 4 fns in sync:
1605 // - create_llargs_for_fn_args.
1608 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1614 param_substs: Option<@param_substs>,
1617 for param_substs.iter().advance |p| { p.validate(); }
1619 debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1621 path_str(ccx.sess, path),
1623 param_substs.repr(ccx.tcx));
1625 let substd_output_type = match param_substs {
1626 None => output_type,
1628 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1631 let is_immediate = ty::type_is_immediate(ccx.tcx, substd_output_type);
1632 let fcx = @mut fn_ctxt_ {
1635 llvm::LLVMGetUndef(Type::i8p().to_ref())
1638 llstaticallocas: None,
1644 has_immediate_return_value: is_immediate,
1645 llargs: @mut HashMap::new(),
1646 lllocals: @mut HashMap::new(),
1647 llupvars: @mut HashMap::new(),
1649 param_substs: param_substs,
1654 fcx.llenv = unsafe {
1655 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1657 if !ty::type_is_nil(substd_output_type) && !(is_immediate && skip_retptr) {
1658 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1663 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1669 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, sp)
1672 // NB: must keep 4 fns in sync:
1675 // - create_llargs_for_fn_args.
1679 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1680 // allocas created for them.
1682 // When we translate a function, we need to map its incoming arguments to the
1683 // spaces that have been created for them (by code in the llallocas field of
1684 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1685 // field of the fn_ctxt with
1686 pub fn create_llargs_for_fn_args(cx: fn_ctxt,
1690 let _icx = push_ctxt("create_llargs_for_fn_args");
1693 impl_self(tt, self_mode) => {
1694 cx.llself = Some(ValSelfData {
1697 is_copy: self_mode == ty::ByCopy
1703 // Return an array containing the ValueRefs that we get from
1704 // llvm::LLVMGetParam for each argument.
1705 vec::from_fn(args.len(), |i| {
1707 let arg_n = cx.arg_pos(i);
1709 let llarg = llvm::LLVMGetParam(cx.llfn, arg_n as c_uint);
1711 // FIXME #7260: aliasing should be determined by monomorphized ty::t
1713 // `~` pointers never alias other parameters, because ownership was transferred
1714 ast::ty_uniq(_) => {
1715 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
1717 // FIXME: #6785: `&mut` can only alias `&const` and `@mut`, we should check for
1718 // those in the other parameters and then mark it as `noalias` if there aren't any
1727 pub fn copy_args_to_allocas(fcx: fn_ctxt,
1730 raw_llargs: &[ValueRef],
1731 arg_tys: &[ty::t]) -> block {
1732 let _icx = push_ctxt("copy_args_to_allocas");
1737 let self_val = if slf.is_copy
1738 && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1739 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1740 let alloc = alloc_ty(bcx, slf.t, "__self");
1741 Store(bcx, tmp, alloc);
1744 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1747 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1748 add_clean(bcx, self_val, slf.t);
1753 for uint::range(0, arg_tys.len()) |arg_n| {
1754 let arg_ty = arg_tys[arg_n];
1755 let raw_llarg = raw_llargs[arg_n];
1757 // For certain mode/type combinations, the raw llarg values are passed
1758 // by value. However, within the fn body itself, we want to always
1759 // have all locals and arguments be by-ref so that we can cancel the
1760 // cleanup and for better interaction with LLVM's debug info. So, if
1761 // the argument would be passed by value, we store it into an alloca.
1762 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1763 // the event it's not truly needed.
1764 // only by value if immediate:
1765 let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1766 let alloc = alloc_ty(bcx, arg_ty, "__arg");
1767 Store(bcx, raw_llarg, alloc);
1772 bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1774 if fcx.ccx.sess.opts.extra_debuginfo && fcx_has_nonzero_span(fcx) {
1775 debuginfo::create_argument_metadata(bcx, &args[arg_n], args[arg_n].ty.span);
1782 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1783 // and builds the return block.
1784 pub fn finish_fn(fcx: fn_ctxt, lltop: BasicBlockRef, last_bcx: block) {
1785 let _icx = push_ctxt("finish_fn");
1786 tie_up_header_blocks(fcx, lltop);
1788 let ret_cx = match fcx.llreturn {
1790 if !last_bcx.terminated {
1791 Br(last_bcx, llreturn);
1793 raw_block(fcx, false, llreturn)
1797 build_return_block(fcx, ret_cx);
1800 // Builds the return block for a function.
1801 pub fn build_return_block(fcx: fn_ctxt, ret_cx: block) {
1802 // Return the value if this function immediate; otherwise, return void.
1803 if fcx.llretptr.is_some() && fcx.has_immediate_return_value {
1804 Ret(ret_cx, Load(ret_cx, fcx.llretptr.get()))
1810 pub fn tie_up_header_blocks(fcx: fn_ctxt, lltop: BasicBlockRef) {
1811 let _icx = push_ctxt("tie_up_header_blocks");
1812 let llnext = match fcx.llloadenv {
1815 llvm::LLVMMoveBasicBlockBefore(ll, lltop);
1817 Br(raw_block(fcx, false, ll), lltop);
1822 match fcx.llstaticallocas {
1825 llvm::LLVMMoveBasicBlockBefore(ll, llnext);
1827 Br(raw_block(fcx, false, ll), llnext);
1833 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1835 // trans_closure: Builds an LLVM function out of a source function.
1836 // If the function closes over its environment a closure will be
1838 pub fn trans_closure(ccx: @mut CrateContext,
1840 decl: &ast::fn_decl,
1844 param_substs: Option<@param_substs>,
1846 attributes: &[ast::Attribute],
1848 maybe_load_env: &fn(fn_ctxt),
1849 finish: &fn(block)) {
1850 ccx.stats.n_closures += 1;
1851 let _icx = push_ctxt("trans_closure");
1852 set_uwtable(llfndecl);
1854 debug!("trans_closure(..., param_substs=%s)",
1855 param_substs.repr(ccx.tcx));
1857 // Set up arguments to the function.
1858 let fcx = new_fn_ctxt_w_id(ccx,
1866 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1868 // Set the fixed stack segment flag if necessary.
1869 if attr::contains_name(attributes, "fixed_stack_segment") {
1870 set_no_inline(fcx.llfn);
1871 set_fixed_stack_segment(fcx.llfn);
1874 // Create the first basic block in the function and keep a handle on it to
1875 // pass to finish_fn later.
1876 let bcx_top = top_scope_block(fcx, body.info());
1877 let mut bcx = bcx_top;
1878 let lltop = bcx.llbb;
1879 let block_ty = node_id_type(bcx, body.id);
1881 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1882 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1884 maybe_load_env(fcx);
1886 // This call to trans_block is the place where we bridge between
1887 // translation calls that don't have a return value (trans_crate,
1888 // trans_mod, trans_item, et cetera) and those that do
1889 // (trans_block, trans_expr, et cetera).
1890 if body.expr.is_none() || ty::type_is_bot(block_ty) ||
1891 ty::type_is_nil(block_ty)
1893 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1895 let dest = expr::SaveIn(fcx.llretptr.get());
1896 bcx = controlflow::trans_block(bcx, body, dest);
1900 match fcx.llreturn {
1901 Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1902 None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1905 // Put return block after all other blocks.
1906 // This somewhat improves single-stepping experience in debugger.
1908 for fcx.llreturn.iter().advance |&llreturn| {
1909 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1913 // Insert the mandatory first few basic blocks before lltop.
1914 finish_fn(fcx, lltop, bcx);
1917 // trans_fn: creates an LLVM function corresponding to a source language
1919 pub fn trans_fn(ccx: @mut CrateContext,
1921 decl: &ast::fn_decl,
1925 param_substs: Option<@param_substs>,
1927 attrs: &[ast::Attribute]) {
1929 let the_path_str = path_str(ccx.sess, path);
1930 let _s = StatRecorder::new(ccx, the_path_str);
1931 debug!("trans_fn(self_arg=%?, param_substs=%s)",
1933 param_substs.repr(ccx.tcx));
1934 let _icx = push_ctxt("trans_fn");
1935 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1947 if ccx.sess.opts.extra_debuginfo
1948 && fcx_has_nonzero_span(fcx) {
1949 debuginfo::create_function_metadata(fcx);
1955 fn insert_synthetic_type_entries(bcx: block,
1956 fn_args: &[ast::arg],
1960 * For tuple-like structs and enum-variants, we generate
1961 * synthetic AST nodes for the arguments. These have no types
1962 * in the type table and no entries in the moves table,
1963 * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
1964 * gets upset. This hack of a function bridges the gap by inserting types.
1966 * This feels horrible. I think we should just have a special path
1967 * for these functions and not try to use the generic code, but
1968 * that's not the problem I'm trying to solve right now. - nmatsakis
1971 let tcx = bcx.tcx();
1972 for uint::range(0, fn_args.len()) |i| {
1973 debug!("setting type of argument %u (pat node %d) to %s",
1974 i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
1976 let pat_id = fn_args[i].pat.id;
1977 let arg_ty = arg_tys[i];
1978 tcx.node_types.insert(pat_id as uint, arg_ty);
1982 pub fn trans_enum_variant(ccx: @mut CrateContext,
1983 _enum_id: ast::node_id,
1984 variant: &ast::variant,
1985 args: &[ast::variant_arg],
1987 param_substs: Option<@param_substs>,
1988 llfndecl: ValueRef) {
1989 let _icx = push_ctxt("trans_enum_variant");
1991 trans_enum_variant_or_tuple_like_struct(
2000 pub fn trans_tuple_struct(ccx: @mut CrateContext,
2001 fields: &[@ast::struct_field],
2002 ctor_id: ast::node_id,
2003 param_substs: Option<@param_substs>,
2004 llfndecl: ValueRef) {
2005 let _icx = push_ctxt("trans_tuple_struct");
2007 trans_enum_variant_or_tuple_like_struct(
2017 fn id(&self) -> ast::node_id;
2018 fn ty<'a>(&'a self) -> &'a ast::Ty;
2021 impl IdAndTy for ast::variant_arg {
2022 fn id(&self) -> ast::node_id { self.id }
2023 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
2026 impl IdAndTy for @ast::struct_field {
2027 fn id(&self) -> ast::node_id { self.node.id }
2028 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
2031 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2032 ccx: @mut CrateContext,
2033 ctor_id: ast::node_id,
2036 param_substs: Option<@param_substs>,
2039 // Translate variant arguments to function arguments.
2040 let fn_args = do args.map |varg| {
2043 ty: (*varg.ty()).clone(),
2044 pat: ast_util::ident_to_pat(
2045 ccx.tcx.sess.next_node_id(),
2046 codemap::dummy_sp(),
2047 special_idents::arg),
2052 let no_substs: &[ty::t] = [];
2053 let ty_param_substs = match param_substs {
2054 Some(ref substs) => {
2055 let v: &[ty::t] = substs.tys;
2059 let v: &[ty::t] = no_substs;
2064 let ctor_ty = ty::subst_tps(ccx.tcx,
2067 ty::node_id_to_type(ccx.tcx, ctor_id));
2069 let result_ty = match ty::get(ctor_ty).sty {
2070 ty::ty_bare_fn(ref bft) => bft.sig.output,
2072 fmt!("trans_enum_variant_or_tuple_like_struct: \
2073 unexpected ctor return type %s",
2074 ty_to_str(ccx.tcx, ctor_ty)))
2077 let fcx = new_fn_ctxt_w_id(ccx,
2086 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2088 let bcx = top_scope_block(fcx, None);
2089 let lltop = bcx.llbb;
2090 let arg_tys = ty::ty_fn_args(ctor_ty);
2092 insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2093 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2095 let repr = adt::represent_type(ccx, result_ty);
2096 adt::trans_start_init(bcx, repr, fcx.llretptr.get(), disr);
2097 for fn_args.iter().enumerate().advance |(i, fn_arg)| {
2098 let lldestptr = adt::trans_field_ptr(bcx,
2103 let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2104 let arg_ty = arg_tys[i];
2105 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2107 finish_fn(fcx, lltop, bcx);
2110 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2111 id: ast::node_id, vi: @~[@ty::VariantInfo],
2113 for enum_definition.variants.iter().advance |variant| {
2114 let disr_val = vi[*i].disr_val;
2117 match variant.node.kind {
2118 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2119 let llfn = get_item_val(ccx, variant.node.id);
2120 trans_enum_variant(ccx, id, variant, *args,
2121 disr_val, None, llfn);
2123 ast::tuple_variant_kind(_) => {
2126 ast::struct_variant_kind(struct_def) => {
2127 trans_struct_def(ccx, struct_def);
2133 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2134 let _icx = push_ctxt("trans_item");
2135 let path = match ccx.tcx.items.get_copy(&item.id) {
2136 ast_map::node_item(_, p) => p,
2138 _ => fail!("trans_item"),
2141 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2142 if purity == ast::extern_fn {
2143 let llfndecl = get_item_val(ccx, item.id);
2144 foreign::trans_foreign_fn(ccx,
2145 vec::append((*path).clone(),
2146 [path_name(item.ident)]),
2151 } else if !generics.is_type_parameterized() {
2152 let llfndecl = get_item_val(ccx, item.id);
2154 vec::append((*path).clone(), [path_name(item.ident)]),
2163 for body.stmts.iter().advance |stmt| {
2165 ast::stmt_decl(@codemap::spanned { node: ast::decl_item(i),
2174 ast::item_impl(ref generics, _, _, ref ms) => {
2175 meth::trans_impl(ccx,
2182 ast::item_mod(ref m) => {
2185 ast::item_enum(ref enum_definition, ref generics) => {
2186 if !generics.is_type_parameterized() {
2187 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2189 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2192 ast::item_static(_, m, expr) => {
2193 consts::trans_const(ccx, m, item.id);
2194 // Do static_assert checking. It can't really be done much earlier because we need to get
2195 // the value of the bool out of LLVM
2196 for item.attrs.iter().advance |attr| {
2197 if "static_assert" == attr.name() {
2198 if m == ast::m_mutbl {
2199 ccx.sess.span_fatal(expr.span,
2200 "cannot have static_assert on a mutable static");
2202 let v = ccx.const_values.get_copy(&item.id);
2204 if !(llvm::LLVMConstIntGetZExtValue(v) as bool) {
2205 ccx.sess.span_fatal(expr.span, "static assertion failed");
2211 ast::item_foreign_mod(ref foreign_mod) => {
2212 foreign::trans_foreign_mod(ccx, path, foreign_mod);
2214 ast::item_struct(struct_def, ref generics) => {
2215 if !generics.is_type_parameterized() {
2216 trans_struct_def(ccx, struct_def);
2219 _ => {/* fall through */ }
2223 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2224 // If this is a tuple-like struct, translate the constructor.
2225 match struct_def.ctor_id {
2226 // We only need to translate a constructor if there are fields;
2227 // otherwise this is a unit-like struct.
2228 Some(ctor_id) if struct_def.fields.len() > 0 => {
2229 let llfndecl = get_item_val(ccx, ctor_id);
2230 trans_tuple_struct(ccx, struct_def.fields,
2231 ctor_id, None, llfndecl);
2233 Some(_) | None => {}
2237 // Translate a module. Doing this amounts to translating the items in the
2238 // module; there ends up being no artifact (aside from linkage names) of
2239 // separate modules in the compiled program. That's because modules exist
2240 // only as a convenience for humans working with the code, to organize names
2241 // and control visibility.
2242 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2243 let _icx = push_ctxt("trans_mod");
2244 for m.items.iter().advance |item| {
2245 trans_item(ccx, *item);
2249 pub fn register_fn(ccx: @mut CrateContext,
2252 node_id: ast::node_id,
2253 attrs: &[ast::Attribute])
2255 let t = ty::node_id_to_type(ccx.tcx, node_id);
2256 register_fn_full(ccx, sp, path, node_id, attrs, t)
2259 pub fn register_fn_full(ccx: @mut CrateContext,
2262 node_id: ast::node_id,
2263 attrs: &[ast::Attribute],
2266 let llfty = type_of_fn_from_ty(ccx, node_type);
2267 register_fn_fuller(ccx, sp, path, node_id, attrs, node_type,
2268 lib::llvm::CCallConv, llfty)
2271 pub fn register_fn_fuller(ccx: @mut CrateContext,
2274 node_id: ast::node_id,
2275 attrs: &[ast::Attribute],
2277 cc: lib::llvm::CallConv,
2280 debug!("register_fn_fuller creating fn for item %d with path %s",
2282 ast_map::path_to_str(path, token::get_ident_interner()));
2284 let ps = if attr::contains_name(attrs, "no_mangle") {
2285 path_elt_to_str(*path.last(), token::get_ident_interner())
2287 mangle_exported_name(ccx, path, node_type)
2290 let llfn = decl_fn(ccx.llmod, ps, cc, fn_ty);
2291 ccx.item_symbols.insert(node_id, ps);
2293 // FIXME #4404 android JNI hacks
2294 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2295 (*ccx.sess.building_library &&
2296 ccx.sess.targ_cfg.os == session::os_android));
2298 create_entry_wrapper(ccx, sp, llfn);
2303 pub fn is_entry_fn(sess: &Session, node_id: ast::node_id) -> bool {
2304 match *sess.entry_fn {
2305 Some((entry_id, _)) => node_id == entry_id,
2310 // Create a _rust_main(args: ~[str]) function which will be called from the
2311 // runtime rust_start function
2312 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2313 _sp: span, main_llfn: ValueRef) {
2314 let et = ccx.sess.entry_type.unwrap();
2315 if et == session::EntryMain {
2316 let llfn = create_main(ccx, main_llfn);
2317 create_entry_fn(ccx, llfn, true);
2319 create_entry_fn(ccx, main_llfn, false);
2322 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2323 let nt = ty::mk_nil();
2325 let llfty = type_of_fn(ccx, [], nt);
2326 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2327 lib::llvm::CCallConv, llfty);
2329 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2331 // the args vector built in create_entry_fn will need
2332 // be updated if this assertion starts to fail.
2333 assert!(fcx.has_immediate_return_value);
2335 let bcx = top_scope_block(fcx, None);
2336 let lltop = bcx.llbb;
2339 let llenvarg = unsafe {
2340 let env_arg = fcx.env_arg_pos();
2341 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2343 let args = ~[llenvarg];
2344 Call(bcx, main_llfn, args);
2346 finish_fn(fcx, lltop, bcx);
2350 fn create_entry_fn(ccx: @mut CrateContext,
2351 rust_main: ValueRef,
2352 use_start_lang_item: bool) {
2353 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2356 // FIXME #4404 android JNI hacks
2357 let llfn = if *ccx.sess.building_library {
2358 decl_cdecl_fn(ccx.llmod, "amain", llfty)
2360 let main_name = match ccx.sess.targ_cfg.os {
2361 session::os_win32 => ~"WinMain@16",
2364 decl_cdecl_fn(ccx.llmod, main_name, llfty)
2366 let llbb = str::as_c_str("top", |buf| {
2368 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2371 let bld = ccx.builder.B;
2373 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2375 let crate_map = ccx.crate_map;
2376 let opaque_crate_map = do "crate_map".as_c_str |buf| {
2377 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2380 let (start_fn, args) = if use_start_lang_item {
2381 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2383 Err(s) => { ccx.tcx.sess.fatal(s); }
2385 let start_fn = if start_def_id.crate == ast::local_crate {
2386 get_item_val(ccx, start_def_id.node)
2388 let start_fn_type = csearch::get_type(ccx.tcx,
2390 trans_external_path(ccx, start_def_id, start_fn_type)
2394 let opaque_rust_main = do "rust_main".as_c_str |buf| {
2395 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2399 C_null(Type::opaque_box(ccx).ptr_to()),
2401 llvm::LLVMGetParam(llfn, 0),
2402 llvm::LLVMGetParam(llfn, 1),
2408 debug!("using user-defined start fn");
2410 C_null(Type::opaque_box(ccx).ptr_to()),
2411 llvm::LLVMGetParam(llfn, 0 as c_uint),
2412 llvm::LLVMGetParam(llfn, 1 as c_uint),
2419 let result = llvm::LLVMBuildCall(bld,
2422 args.len() as c_uint,
2424 llvm::LLVMBuildRet(bld, result);
2429 pub fn fill_fn_pair(bcx: block, pair: ValueRef, llfn: ValueRef,
2430 llenvptr: ValueRef) {
2431 let ccx = bcx.ccx();
2432 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2433 Store(bcx, llfn, code_cell);
2434 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2435 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2436 Store(bcx, llenvblobptr, env_cell);
2439 pub fn item_path(ccx: &CrateContext, i: &ast::item) -> path {
2440 let base = match ccx.tcx.items.get_copy(&i.id) {
2441 ast_map::node_item(_, p) => p,
2442 // separate map for paths?
2443 _ => fail!("item_path")
2445 vec::append((*base).clone(), [path_name(i.ident)])
2448 pub fn get_item_val(ccx: @mut CrateContext, id: ast::node_id) -> ValueRef {
2449 debug!("get_item_val(id=`%?`)", id);
2450 let val = ccx.item_vals.find_copy(&id);
2454 let mut exprt = false;
2455 let item = ccx.tcx.items.get_copy(&id);
2456 let val = match item {
2457 ast_map::node_item(i, pth) => {
2458 let my_path = vec::append((*pth).clone(), [path_name(i.ident)]);
2459 let v = match i.node {
2460 ast::item_static(_, m, expr) => {
2461 let typ = ty::node_id_to_type(ccx.tcx, i.id);
2462 let s = mangle_exported_name(ccx, my_path, typ);
2463 // We need the translated value here, because for enums the
2464 // LLVM type is not fully determined by the Rust type.
2465 let v = consts::const_expr(ccx, expr);
2466 ccx.const_values.insert(id, v);
2467 exprt = m == ast::m_mutbl;
2469 let llty = llvm::LLVMTypeOf(v);
2470 let g = str::as_c_str(s, |buf| {
2471 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2473 ccx.item_symbols.insert(i.id, s);
2477 ast::item_fn(_, purity, _, _, _) => {
2478 let llfn = if purity != ast::extern_fn {
2479 register_fn(ccx, i.span, my_path, i.id, i.attrs)
2481 foreign::register_foreign_fn(ccx,
2487 set_inline_hint_if_appr(i.attrs, llfn);
2490 _ => fail!("get_item_val: weird result in table")
2492 match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2493 Some(sect) => unsafe {
2494 do sect.as_c_str |buf| {
2495 llvm::LLVMSetSection(v, buf);
2502 ast_map::node_trait_method(trait_method, _, pth) => {
2503 debug!("get_item_val(): processing a node_trait_method");
2504 match *trait_method {
2505 ast::required(_) => {
2506 ccx.sess.bug("unexpected variant: required trait method in \
2509 ast::provided(m) => {
2511 register_method(ccx, id, pth, m)
2515 ast_map::node_method(m, _, pth) => {
2516 register_method(ccx, id, pth, m)
2518 ast_map::node_foreign_item(ni, _, _, pth) => {
2521 ast::foreign_item_fn(*) => {
2522 register_fn(ccx, ni.span,
2523 vec::append((*pth).clone(),
2524 [path_name(ni.ident)]),
2528 ast::foreign_item_static(*) => {
2529 let typ = ty::node_id_to_type(ccx.tcx, ni.id);
2530 let ident = token::ident_to_str(&ni.ident);
2531 let g = do str::as_c_str(ident) |buf| {
2533 let ty = type_of(ccx, typ);
2534 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2542 ast_map::node_variant(ref v, enm, pth) => {
2545 ast::tuple_variant_kind(ref args) => {
2546 assert!(args.len() != 0u);
2547 let pth = vec::append((*pth).clone(),
2548 [path_name(enm.ident),
2549 path_name((*v).node.name)]);
2550 llfn = match enm.node {
2551 ast::item_enum(_, _) => {
2552 register_fn(ccx, (*v).span, pth, id, enm.attrs)
2554 _ => fail!("node_variant, shouldn't happen")
2557 ast::struct_variant_kind(_) => {
2558 fail!("struct variant kind unexpected in get_item_val")
2561 set_inline_hint(llfn);
2565 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2566 // Only register the constructor if this is a tuple-like struct.
2567 match struct_def.ctor_id {
2569 ccx.tcx.sess.bug("attempt to register a constructor of \
2570 a non-tuple-like struct")
2573 let llfn = register_fn(ccx,
2575 (*struct_path).clone(),
2578 set_inline_hint(llfn);
2585 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2589 if !exprt && !ccx.reachable.contains(&id) {
2590 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2592 ccx.item_vals.insert(id, val);
2598 pub fn register_method(ccx: @mut CrateContext,
2600 path: @ast_map::path,
2601 m: @ast::method) -> ValueRef {
2602 let mty = ty::node_id_to_type(ccx.tcx, id);
2604 let mut path = (*path).clone();
2605 path.push(path_name(gensym_name("meth")));
2606 path.push(path_name(m.ident));
2608 let llfn = register_fn_full(ccx, m.span, path, id, m.attrs, mty);
2609 set_inline_hint_if_appr(m.attrs, llfn);
2613 // The constant translation pass.
2614 pub fn trans_constant(ccx: &mut CrateContext, it: @ast::item) {
2615 let _icx = push_ctxt("trans_constant");
2617 ast::item_enum(ref enum_definition, _) => {
2618 let vi = ty::enum_variants(ccx.tcx,
2619 ast::def_id { crate: ast::local_crate,
2622 let path = item_path(ccx, it);
2623 for (*enum_definition).variants.iter().advance |variant| {
2624 let p = vec::append(path.clone(), [
2625 path_name(variant.node.name),
2626 path_name(special_idents::descrim)
2628 let s = mangle_exported_name(ccx, p, ty::mk_int()).to_managed();
2629 let disr_val = vi[i].disr_val;
2630 note_unique_llvm_symbol(ccx, s);
2631 let discrim_gvar = str::as_c_str(s, |buf| {
2633 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2637 llvm::LLVMSetInitializer(discrim_gvar, C_int(ccx, disr_val));
2638 llvm::LLVMSetGlobalConstant(discrim_gvar, True);
2640 ccx.discrims.insert(
2641 local_def(variant.node.id), discrim_gvar);
2642 ccx.discrim_symbols.insert(variant.node.id, s);
2650 pub fn trans_constants(ccx: @mut CrateContext, crate: &ast::crate) {
2653 visit::mk_simple_visitor(@visit::SimpleVisitor {
2654 visit_item: |a| trans_constant(ccx, a),
2655 ..*visit::default_simple_visitor()
2659 pub fn vp2i(cx: block, v: ValueRef) -> ValueRef {
2661 return PtrToInt(cx, v, ccx.int_type);
2664 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2666 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2671 ($name:expr, $args:expr, $ret:expr) => ({
2673 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2674 intrinsics.insert(name, f);
2678 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2679 let i8p = Type::i8p();
2680 let mut intrinsics = HashMap::new();
2682 ifn!("llvm.memcpy.p0i8.p0i8.i32",
2683 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2684 ifn!("llvm.memcpy.p0i8.p0i8.i64",
2685 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2686 ifn!("llvm.memmove.p0i8.p0i8.i32",
2687 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2688 ifn!("llvm.memmove.p0i8.p0i8.i64",
2689 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2690 ifn!("llvm.memset.p0i8.i32",
2691 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2692 ifn!("llvm.memset.p0i8.i64",
2693 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2695 ifn!("llvm.trap", [], Type::void());
2696 ifn!("llvm.frameaddress", [Type::i32()], i8p);
2698 ifn!("llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2699 ifn!("llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2700 ifn!("llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2701 ifn!("llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2703 ifn!("llvm.sqrt.f32", [Type::f32()], Type::f32());
2704 ifn!("llvm.sqrt.f64", [Type::f64()], Type::f64());
2705 ifn!("llvm.sin.f32", [Type::f32()], Type::f32());
2706 ifn!("llvm.sin.f64", [Type::f64()], Type::f64());
2707 ifn!("llvm.cos.f32", [Type::f32()], Type::f32());
2708 ifn!("llvm.cos.f64", [Type::f64()], Type::f64());
2709 ifn!("llvm.exp.f32", [Type::f32()], Type::f32());
2710 ifn!("llvm.exp.f64", [Type::f64()], Type::f64());
2711 ifn!("llvm.exp2.f32", [Type::f32()], Type::f32());
2712 ifn!("llvm.exp2.f64", [Type::f64()], Type::f64());
2713 ifn!("llvm.log.f32", [Type::f32()], Type::f32());
2714 ifn!("llvm.log.f64", [Type::f64()], Type::f64());
2715 ifn!("llvm.log10.f32",[Type::f32()], Type::f32());
2716 ifn!("llvm.log10.f64",[Type::f64()], Type::f64());
2717 ifn!("llvm.log2.f32", [Type::f32()], Type::f32());
2718 ifn!("llvm.log2.f64", [Type::f64()], Type::f64());
2720 ifn!("llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2721 ifn!("llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2723 ifn!("llvm.fabs.f32", [Type::f32()], Type::f32());
2724 ifn!("llvm.fabs.f64", [Type::f64()], Type::f64());
2725 ifn!("llvm.floor.f32",[Type::f32()], Type::f32());
2726 ifn!("llvm.floor.f64",[Type::f64()], Type::f64());
2727 ifn!("llvm.ceil.f32", [Type::f32()], Type::f32());
2728 ifn!("llvm.ceil.f64", [Type::f64()], Type::f64());
2729 ifn!("llvm.trunc.f32",[Type::f32()], Type::f32());
2730 ifn!("llvm.trunc.f64",[Type::f64()], Type::f64());
2732 ifn!("llvm.ctpop.i8", [Type::i8()], Type::i8());
2733 ifn!("llvm.ctpop.i16",[Type::i16()], Type::i16());
2734 ifn!("llvm.ctpop.i32",[Type::i32()], Type::i32());
2735 ifn!("llvm.ctpop.i64",[Type::i64()], Type::i64());
2737 ifn!("llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2738 ifn!("llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2739 ifn!("llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2740 ifn!("llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2742 ifn!("llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2743 ifn!("llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2744 ifn!("llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2745 ifn!("llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2747 ifn!("llvm.bswap.i16",[Type::i16()], Type::i16());
2748 ifn!("llvm.bswap.i32",[Type::i32()], Type::i32());
2749 ifn!("llvm.bswap.i64",[Type::i64()], Type::i64());
2754 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2755 ifn!("llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2756 ifn!("llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2759 pub fn trap(bcx: block) {
2760 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2761 Some(&x) => { Call(bcx, x, []); },
2762 _ => bcx.sess().bug("unbound llvm.trap in trap")
2766 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2767 if !ccx.sess.opts.gc || !ccx.uses_gc {
2771 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2772 let gc_metadata = do str::as_c_str(gc_metadata_name) |buf| {
2774 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2778 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2779 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2780 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2784 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2785 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2786 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2787 let map = do "_rust_mod_map".as_c_str |buf| {
2789 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2792 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2793 let mut elts: ~[ValueRef] = ~[];
2795 // This is not ideal, but the borrow checker doesn't
2796 // like the multiple borrows. At least, it doesn't
2797 // like them on the current snapshot. (2013-06-14)
2799 for ccx.module_data.each_key |k| {
2800 keys.push(k.to_managed());
2803 for keys.iter().advance |key| {
2804 let val = *ccx.module_data.find_equiv(key).get();
2805 let s_const = C_cstr(ccx, *key);
2806 let s_ptr = p2i(ccx, s_const);
2807 let v_ptr = p2i(ccx, val);
2808 let elt = C_struct([s_ptr, v_ptr]);
2811 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2814 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2820 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2821 llmod: ModuleRef) -> ValueRef {
2822 let targ_cfg = sess.targ_cfg;
2823 let int_type = Type::int(targ_cfg.arch);
2824 let mut n_subcrates = 1;
2825 let cstore = sess.cstore;
2826 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2827 let mapname = if *sess.building_library {
2828 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2832 let sym_name = ~"_rust_crate_map_" + mapname;
2833 let arrtype = Type::array(&int_type, n_subcrates as u64);
2834 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2835 let map = str::as_c_str(sym_name, |buf| {
2837 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2840 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2844 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2845 let mut subcrates: ~[ValueRef] = ~[];
2847 let cstore = ccx.sess.cstore;
2848 while cstore::have_crate_data(cstore, i) {
2849 let cdata = cstore::get_crate_data(cstore, i);
2850 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2852 cstore::get_crate_vers(cstore, i),
2853 cstore::get_crate_hash(cstore, i));
2854 let cr = str::as_c_str(nm, |buf| {
2856 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2859 subcrates.push(p2i(ccx, cr));
2862 subcrates.push(C_int(ccx, 0));
2864 let llannihilatefn = match ccx.tcx.lang_items.annihilate_fn() {
2865 Some(annihilate_def_id) => {
2866 if annihilate_def_id.crate == ast::local_crate {
2867 get_item_val(ccx, annihilate_def_id.node)
2869 let annihilate_fn_type = csearch::get_type(ccx.tcx,
2870 annihilate_def_id).ty;
2871 trans_external_path(ccx, annihilate_def_id, annihilate_fn_type)
2874 None => { C_null(Type::i8p()) }
2878 let mod_map = create_module_map(ccx);
2879 llvm::LLVMSetInitializer(map, C_struct(
2881 lib::llvm::llvm::LLVMConstPointerCast(llannihilatefn, Type::i8p().to_ref()),
2883 C_array(ccx.int_type, subcrates)]));
2887 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
2888 -> encoder::EncodeParams<'r> {
2890 let diag = cx.sess.diagnostic();
2891 let item_symbols = &cx.item_symbols;
2892 let discrim_symbols = &cx.discrim_symbols;
2893 let link_meta = &cx.link_meta;
2894 encoder::EncodeParams {
2897 reexports2: cx.exp_map2,
2898 item_symbols: item_symbols,
2899 discrim_symbols: discrim_symbols,
2900 link_meta: link_meta,
2901 cstore: cx.sess.cstore,
2902 encode_inlined_item: ie,
2903 reachable: cx.reachable,
2907 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::crate) {
2908 if !*cx.sess.building_library { return; }
2910 let encode_inlined_item: encoder::encode_inlined_item =
2911 |ecx, ebml_w, path, ii|
2912 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
2914 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2915 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
2916 let llconst = C_struct([llmeta]);
2917 let mut llglobal = str::as_c_str("rust_metadata", |buf| {
2919 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
2923 llvm::LLVMSetInitializer(llglobal, llconst);
2924 str::as_c_str(cx.sess.targ_cfg.target_strs.meta_sect_name, |buf| {
2925 llvm::LLVMSetSection(llglobal, buf)
2927 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2929 let t_ptr_i8 = Type::i8p();
2930 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
2931 let llvm_used = do "llvm.used".as_c_str |buf| {
2932 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
2934 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
2935 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
2939 fn mk_global(ccx: &CrateContext,
2945 let llglobal = do str::as_c_str(name) |buf| {
2946 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
2948 llvm::LLVMSetInitializer(llglobal, llval);
2949 llvm::LLVMSetGlobalConstant(llglobal, True);
2952 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
2959 // Writes the current ABI version into the crate.
2960 pub fn write_abi_version(ccx: &mut CrateContext) {
2961 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
2964 pub fn trans_crate(sess: session::Session,
2968 emap2: resolve::ExportMap2,
2969 reachable_map: @mut HashSet<ast::node_id>,
2970 maps: astencode::Maps)
2971 -> (ContextRef, ModuleRef, LinkMeta) {
2972 // Before we touch LLVM, make sure that multithreading is enabled.
2973 if unsafe { !llvm::LLVMRustStartMultithreading() } {
2974 //sess.bug("couldn't enable multi-threaded LLVM");
2977 let mut symbol_hasher = hash::default_state();
2978 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
2980 // Append ".rc" to crate name as LLVM module identifier.
2982 // LLVM code generator emits a ".file filename" directive
2983 // for ELF backends. Value of the "filename" is set as the
2984 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2985 // crashes if the module identifer is same as other symbols
2986 // such as a function name in the module.
2987 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2988 let llmod_id = link_meta.name.to_owned() + ".rc";
2990 let ccx = @mut CrateContext::new(sess,
3000 let _icx = push_ctxt("data");
3001 trans_constants(ccx, crate);
3005 let _icx = push_ctxt("text");
3006 trans_mod(ccx, &crate.node.module);
3009 decl_gc_metadata(ccx, llmod_id);
3010 fill_crate_map(ccx, ccx.crate_map);
3011 glue::emit_tydescs(ccx);
3012 write_abi_version(ccx);
3013 if ccx.sess.opts.debuginfo {
3014 debuginfo::finalize(ccx);
3017 // Translate the metadata.
3018 write_metadata(ccx, crate);
3019 if ccx.sess.trans_stats() {
3020 io::println("--- trans stats ---");
3021 io::println(fmt!("n_static_tydescs: %u",
3022 ccx.stats.n_static_tydescs));
3023 io::println(fmt!("n_glues_created: %u",
3024 ccx.stats.n_glues_created));
3025 io::println(fmt!("n_null_glues: %u", ccx.stats.n_null_glues));
3026 io::println(fmt!("n_real_glues: %u", ccx.stats.n_real_glues));
3028 io::println(fmt!("n_fns: %u", ccx.stats.n_fns));
3029 io::println(fmt!("n_monos: %u", ccx.stats.n_monos));
3030 io::println(fmt!("n_inlines: %u", ccx.stats.n_inlines));
3031 io::println(fmt!("n_closures: %u", ccx.stats.n_closures));
3032 io::println("fn stats:");
3033 do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3036 for ccx.stats.fn_stats.iter().advance |tuple| {
3038 (ref name, ms, insns) => {
3039 io::println(fmt!("%u insns, %u ms, %s", insns, ms, *name));
3044 if ccx.sess.count_llvm_insns() {
3045 for ccx.stats.llvm_insns.iter().advance |(k, v)| {
3046 io::println(fmt!("%-7u %s", *v, *k));
3050 let llcx = ccx.llcx;
3051 let link_meta = ccx.link_meta;
3052 let llmod = ccx.llmod;
3054 return (llcx, llmod, link_meta);