1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // trans.rs: Translate the completed AST to the LLVM IR.
13 // Some functions here, such as trans_block and trans_expr, return a value --
14 // the result of the translation to LLVM -- while others, such as trans_fn,
15 // trans_impl, and trans_item, are called only for the side effect of adding a
16 // particular definition to the LLVM IR output we're producing.
18 // Hopefully useful general knowledge about trans:
20 // * There's no way to find out the ty::t type of a ValueRef. Doing so
21 // would be "trying to get the eggs out of an omelette" (credit:
22 // pcwalton). You can, instead, find out its TypeRef by calling val_ty,
23 // but many TypeRefs correspond to one ty::t; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
27 use back::link::{mangle_exported_name};
28 use back::{link, abi};
30 use driver::session::Session;
31 use driver::driver::{CrateAnalysis, CrateTranslation};
32 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
38 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
39 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::base;
43 use middle::trans::build::*;
44 use middle::trans::builder::{Builder, noname};
45 use middle::trans::callee;
46 use middle::trans::common::*;
47 use middle::trans::consts;
48 use middle::trans::controlflow;
49 use middle::trans::datum;
50 use middle::trans::debuginfo;
51 use middle::trans::expr;
52 use middle::trans::foreign;
53 use middle::trans::glue;
54 use middle::trans::inline;
55 use middle::trans::llrepr::LlvmRepr;
56 use middle::trans::machine;
57 use middle::trans::machine::{llalign_of_min, llsize_of};
58 use middle::trans::meth;
59 use middle::trans::monomorphize;
60 use middle::trans::tvec;
61 use middle::trans::type_of;
62 use middle::trans::type_of::*;
63 use middle::trans::value::Value;
65 use util::common::indenter;
66 use util::ppaux::{Repr, ty_to_str};
68 use middle::trans::type_::Type;
70 use std::c_str::ToCStr;
72 use std::hashmap::HashMap;
74 use std::libc::c_uint;
79 use syntax::ast::Name;
80 use syntax::ast_map::{path, path_elt_to_str, path_name, path_pretty_name};
81 use syntax::ast_util::{local_def};
83 use syntax::attr::AttrMetaMethods;
84 use syntax::codemap::Span;
85 use syntax::parse::token;
86 use syntax::parse::token::{special_idents};
87 use syntax::print::pprust::stmt_to_str;
88 use syntax::{ast, ast_util, codemap, ast_map};
89 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
91 use syntax::visit::Visitor;
93 pub use middle::trans::context::task_llcx;
95 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
97 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
98 let opt = local_data::get(task_local_insn_key, |k| k.map_move(|k| *k));
104 pub fn init_insn_ctxt() {
105 local_data::set(task_local_insn_key, @~[]);
108 pub struct _InsnCtxt { _x: () }
111 impl Drop for _InsnCtxt {
113 do local_data::modify(task_local_insn_key) |c| {
114 do c.map_move |ctx| {
115 let mut ctx = (*ctx).clone();
123 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
124 debug!("new InsnCtxt: %s", s);
125 do local_data::modify(task_local_insn_key) |c| {
126 do c.map_move |ctx| {
127 let mut ctx = (*ctx).clone();
135 struct StatRecorder<'self> {
136 ccx: @mut CrateContext,
142 impl<'self> StatRecorder<'self> {
143 pub fn new(ccx: @mut CrateContext,
144 name: &'self str) -> StatRecorder<'self> {
145 let start = if ccx.sess.trans_stats() {
146 time::precise_time_ns()
150 let istart = ccx.stats.n_llvm_insns;
161 impl<'self> Drop for StatRecorder<'self> {
163 if self.ccx.sess.trans_stats() {
164 let end = time::precise_time_ns();
165 let elapsed = ((end - self.start) / 1_000_000) as uint;
166 let iend = self.ccx.stats.n_llvm_insns;
167 self.ccx.stats.fn_stats.push((self.name.to_owned(),
169 iend - self.istart));
170 self.ccx.stats.n_fns += 1;
171 // Reset LLVM insn count to avoid compound costs.
172 self.ccx.stats.n_llvm_insns = self.istart;
177 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
178 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
179 let llfn: ValueRef = do name.with_c_str |buf| {
181 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
185 lib::llvm::SetFunctionCallConv(llfn, cc);
189 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
190 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
191 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
194 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
195 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: &str,
196 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
197 match externs.find_equiv(&name) {
198 Some(n) => return *n,
201 let f = decl_fn(llmod, name, cc, ty);
202 externs.insert(name.to_owned(), f);
206 pub fn get_extern_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t,
207 name: &str) -> ValueRef {
208 match ccx.externs.find_equiv(&name) {
209 Some(n) => return *n,
212 let f = decl_rust_fn(ccx, inputs, output, name);
213 ccx.externs.insert(name.to_owned(), f);
217 pub fn decl_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t,
218 name: &str) -> ValueRef {
219 let llfty = type_of_rust_fn(ccx, inputs, output);
220 let llfn = decl_cdecl_fn(ccx.llmod, name, llfty);
222 match ty::get(output).sty {
223 // `~` pointer return values never alias because ownership is transferred
225 ty::ty_evec(_, ty::vstore_uniq) => {
227 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
233 let uses_outptr = type_of::return_uses_outptr(ccx.tcx, output);
234 let offset = if uses_outptr { 2 } else { 1 };
236 for (i, &arg_ty) in inputs.iter().enumerate() {
237 let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
238 match ty::get(arg_ty).sty {
239 // `~` pointer parameters never alias because ownership is transferred
241 ty::ty_evec(_, ty::vstore_uniq) |
242 ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, _}) => {
244 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
251 // The out pointer will never alias with any other pointers, as the object only exists at a
252 // language level after the call. It can also be tagged with SRet to indicate that it is
253 // guaranteed to point to a usable block of memory for the type.
256 let outptr = llvm::LLVMGetParam(llfn, 0);
257 llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
258 llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
265 pub fn decl_internal_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t,
266 name: &str) -> ValueRef {
267 let llfn = decl_rust_fn(ccx, inputs, output, name);
268 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
272 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
273 name: &str, ty: Type) -> ValueRef {
274 match externs.find_equiv(&name) {
275 Some(n) => return *n,
279 let c = do name.with_c_str |buf| {
280 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
282 externs.insert(name.to_owned(), c);
286 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
287 let _icx = push_ctxt("umax");
288 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
289 return Select(cx, cond, b, a);
292 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
293 let _icx = push_ctxt("umin");
294 let cond = ICmp(cx, lib::llvm::IntULT, a, b);
295 return Select(cx, cond, a, b);
298 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
299 // The type of the returned pointer is always i8*. If you care about the
300 // return type, use bump_ptr().
301 pub fn ptr_offs(bcx: @mut Block, base: ValueRef, sz: ValueRef) -> ValueRef {
302 let _icx = push_ctxt("ptr_offs");
303 let raw = PointerCast(bcx, base, Type::i8p());
304 InBoundsGEP(bcx, raw, [sz])
307 // Increment a pointer by a given amount and then cast it to be a pointer
309 pub fn bump_ptr(bcx: @mut Block, t: ty::t, base: ValueRef, sz: ValueRef) ->
311 let _icx = push_ctxt("bump_ptr");
313 let bumped = ptr_offs(bcx, base, sz);
314 let typ = type_of(ccx, t).ptr_to();
315 PointerCast(bcx, bumped, typ)
318 // Returns a pointer to the body for the box. The box may be an opaque
319 // box. The result will be casted to the type of body_t, if it is statically
322 // The runtime equivalent is box_body() in "rust_internal.h".
323 pub fn opaque_box_body(bcx: @mut Block,
325 boxptr: ValueRef) -> ValueRef {
326 let _icx = push_ctxt("opaque_box_body");
328 let ty = type_of(ccx, body_t);
329 let ty = Type::box(ccx, &ty);
330 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
331 GEPi(bcx, boxptr, [0u, abi::box_field_body])
334 // malloc_raw_dyn: allocates a box to contain a given type, but with a
335 // potentially dynamic size.
336 pub fn malloc_raw_dyn(bcx: @mut Block,
339 size: ValueRef) -> Result {
340 let _icx = push_ctxt("malloc_raw");
343 fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::DefId {
344 let li = &bcx.tcx().lang_items;
345 match li.require(it) {
348 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
349 bcx.ty_to_str(t), s));
354 if heap == heap_exchange {
355 let llty_value = type_of::type_of(ccx, t);
359 let r = callee::trans_lang_call(
361 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
364 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
366 // we treat ~fn, @fn and @[] as @ here, which isn't ideal
367 let (mk_fn, langcall) = match heap {
368 heap_managed | heap_managed_unique => {
370 require_alloc_fn(bcx, t, MallocFnLangItem))
372 heap_exchange_closure => {
374 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
376 _ => fail!("heap_exchange already handled")
379 // Grab the TypeRef type of box_ptr_ty.
380 let box_ptr_ty = mk_fn(bcx.tcx(), t);
381 let llty = type_of(ccx, box_ptr_ty);
383 // Get the tydesc for the body:
384 let static_ti = get_tydesc(ccx, t);
385 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
388 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
389 let r = callee::trans_lang_call(
394 let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
395 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
400 // malloc_raw: expects an unboxed type and returns a pointer to
401 // enough space for a box of that type. This includes a rust_opaque_box
403 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
404 let ty = type_of(bcx.ccx(), t);
405 let size = llsize_of(bcx.ccx(), ty);
406 malloc_raw_dyn(bcx, t, heap, size)
409 pub struct MallocResult {
415 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
416 // and pulls out the body
417 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
419 assert!(heap != heap_exchange);
420 let _icx = push_ctxt("malloc_general");
421 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
422 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
424 MallocResult { bcx: bcx, box: llbox, body: body }
427 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
428 let ty = type_of(bcx.ccx(), t);
429 assert!(heap != heap_exchange);
430 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
432 pub fn malloc_boxed(bcx: @mut Block, t: ty::t)
434 malloc_general(bcx, t, heap_managed)
437 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
438 if ty::type_contents(bcx.tcx(), t).contains_managed() {
445 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
446 assert!(heap != heap_exchange);
447 if heap == heap_managed_unique {
448 // In cases where we are looking at a unique-typed allocation in the
449 // managed heap (thus have refcount 1 from the managed allocator),
450 // such as a ~(@foo) or such. These need to have their refcount forced
451 // to -2 so the annihilator ignores them.
452 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
453 let rc_val = C_int(bcx.ccx(), -2);
454 Store(bcx, rc_val, rc);
458 // Type descriptor and type glue stuff
460 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
461 get_tydesc(ccx, t).tydesc
464 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
465 match ccx.tydescs.find(&t) {
472 ccx.stats.n_static_tydescs += 1u;
473 let inf = glue::declare_tydesc(ccx, t);
474 ccx.tydescs.insert(t, inf);
478 pub fn set_optimize_for_size(f: ValueRef) {
479 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
482 pub fn set_no_inline(f: ValueRef) {
483 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
486 pub fn set_no_unwind(f: ValueRef) {
487 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
490 // Tell LLVM to emit the information necessary to unwind the stack for the
492 pub fn set_uwtable(f: ValueRef) {
493 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
496 pub fn set_inline_hint(f: ValueRef) {
497 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
500 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
502 // Set the inline hint if there is one
503 match find_inline_attr(attrs) {
504 InlineHint => set_inline_hint(llfn),
505 InlineAlways => set_always_inline(llfn),
506 InlineNever => set_no_inline(llfn),
507 InlineNone => { /* fallthrough */ }
510 // Add the no-split-stack attribute if requested
511 if contains_name(attrs, "no_split_stack") {
512 set_no_split_stack(llfn);
516 pub fn set_always_inline(f: ValueRef) {
517 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
520 pub fn set_fixed_stack_segment(f: ValueRef) {
521 do "fixed-stack-segment".to_c_str().with_ref |buf| {
522 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
526 pub fn set_no_split_stack(f: ValueRef) {
527 do "no-split-stack".to_c_str().with_ref |buf| {
528 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
532 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
533 if ty::type_is_structural(t) {
534 set_optimize_for_size(f);
535 } else { set_always_inline(f); }
538 // Double-check that we never ask LLVM to declare the same symbol twice. It
539 // silently mangles such symbols, breaking our linkage model.
540 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
541 if ccx.all_llvm_symbols.contains(&sym) {
542 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
544 ccx.all_llvm_symbols.insert(sym);
548 pub fn get_res_dtor(ccx: @mut CrateContext,
550 parent_id: ast::DefId,
553 let _icx = push_ctxt("trans_res_dtor");
554 if !substs.is_empty() {
555 let did = if did.crate != ast::LOCAL_CRATE {
556 inline::maybe_instantiate_inline(ccx, did)
560 assert_eq!(did.crate, ast::LOCAL_CRATE);
561 let tsubsts = ty::substs {regions: ty::ErasedRegions,
563 tps: /*bad*/ substs.to_owned() };
564 let (val, _) = monomorphize::monomorphic_fn(ccx,
572 } else if did.crate == ast::LOCAL_CRATE {
573 get_item_val(ccx, did.node)
576 let name = csearch::get_symbol(ccx.sess.cstore, did);
577 let class_ty = ty::subst_tps(tcx,
580 ty::lookup_item_type(tcx, parent_id).ty);
581 let llty = type_of_dtor(ccx, class_ty);
582 get_extern_fn(&mut ccx.externs,
585 lib::llvm::CCallConv,
590 // Structural comparison: a rather involved form of glue.
591 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
592 if cx.sess.opts.save_temps {
593 do s.with_c_str |buf| {
595 llvm::LLVMSetValueName(v, buf)
602 // Used only for creating scalar comparison glue.
603 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
605 // NB: This produces an i1, not a Rust bool (i8).
606 pub fn compare_scalar_types(cx: @mut Block,
612 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
614 match ty::get(t).sty {
615 ty::ty_nil => rslt(cx, f(nil_type)),
616 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
617 ty::ty_char => rslt(cx, f(unsigned_int)),
618 ty::ty_int(_) => rslt(cx, f(signed_int)),
619 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
620 ty::ty_float(_) => rslt(cx, f(floating_point)),
623 controlflow::trans_fail(
625 @"attempt to compare values of type type"),
629 // Should never get here, because t is scalar.
630 cx.sess().bug("non-scalar type passed to \
631 compare_scalar_types")
637 // A helper function to do the actual comparison of scalar values.
638 pub fn compare_scalar_values(cx: @mut Block,
644 let _icx = push_ctxt("compare_scalar_values");
645 fn die(cx: @mut Block) -> ! {
646 cx.tcx().sess.bug("compare_scalar_values: must be a\
647 comparison operator");
651 // We don't need to do actual comparisons for nil.
652 // () == () holds but () < () does not.
654 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(true),
655 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(false),
656 // refinements would be nice
662 ast::BiEq => lib::llvm::RealOEQ,
663 ast::BiNe => lib::llvm::RealUNE,
664 ast::BiLt => lib::llvm::RealOLT,
665 ast::BiLe => lib::llvm::RealOLE,
666 ast::BiGt => lib::llvm::RealOGT,
667 ast::BiGe => lib::llvm::RealOGE,
670 return FCmp(cx, cmp, lhs, rhs);
674 ast::BiEq => lib::llvm::IntEQ,
675 ast::BiNe => lib::llvm::IntNE,
676 ast::BiLt => lib::llvm::IntSLT,
677 ast::BiLe => lib::llvm::IntSLE,
678 ast::BiGt => lib::llvm::IntSGT,
679 ast::BiGe => lib::llvm::IntSGE,
682 return ICmp(cx, cmp, lhs, rhs);
686 ast::BiEq => lib::llvm::IntEQ,
687 ast::BiNe => lib::llvm::IntNE,
688 ast::BiLt => lib::llvm::IntULT,
689 ast::BiLe => lib::llvm::IntULE,
690 ast::BiGt => lib::llvm::IntUGT,
691 ast::BiGe => lib::llvm::IntUGE,
694 return ICmp(cx, cmp, lhs, rhs);
699 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
701 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
702 return Load(cx, GEPi(cx, p, idxs));
705 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
706 Store(cx, v, GEPi(cx, p, idxs));
709 // Iterates through the elements of a structural type.
710 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
711 f: val_and_ty_fn) -> @mut Block {
712 let _icx = push_ctxt("iter_structural_ty");
714 fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
715 variant: @ty::VariantInfo,
716 tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
717 let _icx = push_ctxt("iter_variant");
721 for (i, &arg) in variant.args.iter().enumerate() {
723 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
724 ty::subst_tps(tcx, tps, None, arg));
730 match ty::get(t).sty {
731 ty::ty_struct(*) => {
732 let repr = adt::represent_type(cx.ccx(), t);
733 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
734 for (i, field_ty) in field_tys.iter().enumerate() {
735 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
736 cx = f(cx, llfld_a, field_ty.mt.ty);
740 ty::ty_estr(ty::vstore_fixed(_)) |
741 ty::ty_evec(_, ty::vstore_fixed(_)) => {
742 let (base, len) = tvec::get_base_and_len(cx, av, t);
743 cx = tvec::iter_vec_raw(cx, base, t, len, f);
745 ty::ty_tup(ref args) => {
746 let repr = adt::represent_type(cx.ccx(), t);
747 for (i, arg) in args.iter().enumerate() {
748 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
749 cx = f(cx, llfld_a, *arg);
752 ty::ty_enum(tid, ref substs) => {
755 let repr = adt::represent_type(ccx, t);
756 let variants = ty::enum_variants(ccx.tcx, tid);
757 let n_variants = (*variants).len();
759 // NB: we must hit the discriminant first so that structural
760 // comparison know not to proceed when the discriminants differ.
762 match adt::trans_switch(cx, repr, av) {
763 (_match::single, None) => {
764 cx = iter_variant(cx, repr, av, variants[0],
767 (_match::switch, Some(lldiscrim_a)) => {
768 cx = f(cx, lldiscrim_a, ty::mk_int());
769 let unr_cx = sub_block(cx, "enum-iter-unr");
771 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
773 let next_cx = sub_block(cx, "enum-iter-next");
775 for variant in (*variants).iter() {
777 sub_block(cx, ~"enum-iter-variant-" +
778 variant.disr_val.to_str());
780 iter_variant(variant_cx, repr, av, *variant,
781 substs.tps, |x,y,z| f(x,y,z));
782 match adt::trans_case(cx, repr, variant.disr_val) {
783 _match::single_result(r) => {
784 AddCase(llswitch, r.val, variant_cx.llbb)
786 _ => ccx.sess.unimpl("value from adt::trans_case \
787 in iter_structural_ty")
789 Br(variant_cx, next_cx.llbb);
793 _ => ccx.sess.unimpl("value from adt::trans_switch \
794 in iter_structural_ty")
797 _ => cx.sess().unimpl("type in iter_structural_ty")
802 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::BinOp,
803 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
804 cast_shift_rhs(op, lhs, rhs,
805 |a,b| Trunc(cx, a, b),
806 |a,b| ZExt(cx, a, b))
809 pub fn cast_shift_const_rhs(op: ast::BinOp,
810 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
811 cast_shift_rhs(op, lhs, rhs,
812 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
813 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
816 pub fn cast_shift_rhs(op: ast::BinOp,
817 lhs: ValueRef, rhs: ValueRef,
818 trunc: &fn(ValueRef, Type) -> ValueRef,
819 zext: &fn(ValueRef, Type) -> ValueRef)
821 // Shifts may have any size int on the rhs
823 if ast_util::is_shift_binop(op) {
824 let rhs_llty = val_ty(rhs);
825 let lhs_llty = val_ty(lhs);
826 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
827 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
830 } else if lhs_sz > rhs_sz {
831 // FIXME (#1877: If shifting by negative
832 // values becomes not undefined then this is wrong.
843 pub fn fail_if_zero(cx: @mut Block, span: Span, divrem: ast::BinOp,
844 rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
845 let text = if divrem == ast::BiDiv {
846 @"attempted to divide by zero"
848 @"attempted remainder with a divisor of zero"
850 let is_zero = match ty::get(rhs_t).sty {
852 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
853 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
856 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
857 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
860 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
861 ty_to_str(cx.ccx().tcx, rhs_t));
864 do with_cond(cx, is_zero) |bcx| {
865 controlflow::trans_fail(bcx, Some(span), text)
869 pub fn null_env_ptr(ccx: &CrateContext) -> ValueRef {
870 C_null(Type::opaque_box(ccx).ptr_to())
873 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
874 let name = csearch::get_symbol(ccx.sess.cstore, did);
875 match ty::get(t).sty {
876 ty::ty_bare_fn(ref fn_ty) => {
877 match fn_ty.abis.for_arch(ccx.sess.targ_cfg.arch) {
878 Some(Rust) | Some(RustIntrinsic) => {
879 get_extern_rust_fn(ccx, fn_ty.sig.inputs, fn_ty.sig.output, name)
882 let c = foreign::llvm_calling_convention(ccx, fn_ty.abis);
883 let cconv = c.unwrap_or(lib::llvm::CCallConv);
884 let llty = type_of_fn_from_ty(ccx, t);
885 get_extern_fn(&mut ccx.externs, ccx.llmod, name, cconv, llty)
889 ty::ty_closure(ref f) => {
890 get_extern_rust_fn(ccx, f.sig.inputs, f.sig.output, name)
893 let llty = type_of(ccx, t);
894 get_extern_const(&mut ccx.externs, ccx.llmod, name, llty)
899 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef],
900 attributes: &[(uint, lib::llvm::Attribute)])
901 -> (ValueRef, @mut Block) {
902 let _icx = push_ctxt("invoke_");
904 return (C_null(Type::i8()), bcx);
907 match bcx.node_info {
908 None => debug!("invoke at ???"),
910 debug!("invoke at %s",
911 bcx.sess().codemap.span_to_str(node_info.span));
915 if need_invoke(bcx) {
917 debug!("invoking %x at %x",
918 ::std::cast::transmute(llfn),
919 ::std::cast::transmute(bcx.llbb));
920 for &llarg in llargs.iter() {
921 debug!("arg: %x", ::std::cast::transmute(llarg));
924 let normal_bcx = sub_block(bcx, "normal return");
925 let llresult = Invoke(bcx,
929 get_landing_pad(bcx),
931 return (llresult, normal_bcx);
934 debug!("calling %x at %x",
935 ::std::cast::transmute(llfn),
936 ::std::cast::transmute(bcx.llbb));
937 for &llarg in llargs.iter() {
938 debug!("arg: %x", ::std::cast::transmute(llarg));
941 let llresult = Call(bcx, llfn, llargs, attributes);
942 return (llresult, bcx);
946 pub fn need_invoke(bcx: @mut Block) -> bool {
947 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
951 // Avoid using invoke if we are already inside a landing pad.
956 if have_cached_lpad(bcx) {
960 // Walk the scopes to look for cleanups
962 let mut cur_scope = cur.scope;
964 cur_scope = match cur_scope {
966 for cleanup in inf.cleanups.iter() {
968 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
969 if cleanup_type == normal_exit_and_unwind {
978 cur = match cur.parent {
988 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
990 do in_lpad_scope_cx(bcx) |inf| {
991 match inf.landing_pad {
992 Some(_) => res = true,
999 pub fn in_lpad_scope_cx(bcx: @mut Block, f: &fn(si: &mut ScopeInfo)) {
1001 let mut cur_scope = bcx.scope;
1003 cur_scope = match cur_scope {
1005 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
1012 bcx = block_parent(bcx);
1019 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
1020 let _icx = push_ctxt("get_landing_pad");
1022 let mut cached = None;
1023 let mut pad_bcx = bcx; // Guaranteed to be set below
1024 do in_lpad_scope_cx(bcx) |inf| {
1025 // If there is a valid landing pad still around, use it
1026 match inf.landing_pad {
1027 Some(target) => cached = Some(target),
1029 pad_bcx = lpad_block(bcx, "unwind");
1030 inf.landing_pad = Some(pad_bcx.llbb);
1034 // Can't return from block above
1035 match cached { Some(b) => return b, None => () }
1036 // The landing pad return type (the type being propagated). Not sure what
1037 // this represents but it's determined by the personality function and
1038 // this is what the EH proposal example uses.
1039 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
1040 // The exception handling personality function. This is the C++
1041 // personality function __gxx_personality_v0, wrapped in our naming
1043 let personality = bcx.ccx().upcalls.rust_personality;
1044 // The only landing pad clause will be 'cleanup'
1045 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
1046 // The landing pad block is a cleanup
1047 SetCleanup(pad_bcx, llretval);
1049 // Because we may have unwound across a stack boundary, we must call into
1050 // the runtime to figure out which stack segment we are on and place the
1051 // stack limit back into the TLS.
1052 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, [], []);
1054 // We store the retval in a function-central alloca, so that calls to
1055 // Resume can find it.
1056 match bcx.fcx.personality {
1057 Some(addr) => Store(pad_bcx, llretval, addr),
1059 let addr = alloca(pad_bcx, val_ty(llretval), "");
1060 bcx.fcx.personality = Some(addr);
1061 Store(pad_bcx, llretval, addr);
1065 // Unwind all parent scopes, and finish with a Resume instr
1066 cleanup_and_leave(pad_bcx, None, None);
1067 return pad_bcx.llbb;
1070 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::NodeId) -> @mut Block {
1071 let mut bcx_sid = bcx;
1072 let mut cur_scope = bcx_sid.scope;
1074 cur_scope = match cur_scope {
1076 match inf.node_info {
1077 Some(NodeInfo { id, _ }) if id == scope_id => {
1080 // FIXME(#6268, #6248) hacky cleanup for nested method calls
1081 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1088 bcx_sid = match bcx_sid.parent {
1089 None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1090 Some(bcx_par) => bcx_par
1099 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1100 if ty::type_is_bot(t) {
1101 return C_null(Type::i8p());
1103 let llptr = alloc_ty(bcx, t, "");
1104 Store(bcx, v, llptr);
1108 // Since this function does *not* root, it is the caller's responsibility to
1109 // ensure that the referent is pointed to by a root.
1110 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1111 let llptr = alloca(cx, val_ty(v), "");
1112 Store(cx, v, llptr);
1116 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1117 let _icx = push_ctxt("spill_if_immediate");
1118 if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1122 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1123 let _icx = push_ctxt("load_if_immediate");
1124 if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1128 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<Span>, trace_str: @str) {
1129 if !bcx.sess().trace() { return; }
1130 let _icx = push_ctxt("trans_trace");
1131 add_comment(bcx, trace_str);
1132 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1133 let (V_filename, V_line) = match sp_opt {
1135 let sess = bcx.sess();
1136 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1137 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1140 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1143 let ccx = bcx.ccx();
1144 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1145 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1146 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1147 Call(bcx, ccx.upcalls.trace, args, []);
1150 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1151 match local.pat.node {
1152 ast::PatWild => true, _ => false
1156 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1158 debug!("init_local(bcx=%s, local.id=%?)",
1159 bcx.to_str(), local.id);
1160 let _indenter = indenter();
1162 let _icx = push_ctxt("init_local");
1164 if ignore_lhs(bcx, local) {
1165 // Handle let _ = e; just like e;
1168 return expr::trans_into(bcx, init, expr::Ignore);
1170 None => { return bcx; }
1174 _match::store_local(bcx, local.pat, local.init)
1177 pub fn trans_stmt(cx: @mut Block, s: &ast::Stmt) -> @mut Block {
1178 let _icx = push_ctxt("trans_stmt");
1179 debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1181 if cx.sess().asm_comments() {
1182 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1188 ast::StmtExpr(e, _) | ast::StmtSemi(e, _) => {
1189 bcx = expr::trans_into(cx, e, expr::Ignore);
1191 ast::StmtDecl(d, _) => {
1193 ast::DeclLocal(ref local) => {
1194 bcx = init_local(bcx, *local);
1195 if cx.sess().opts.extra_debuginfo {
1196 debuginfo::create_local_var_metadata(bcx, *local);
1199 ast::DeclItem(i) => trans_item(cx.fcx.ccx, i)
1202 ast::StmtMac(*) => cx.tcx().sess.bug("unexpanded macro")
1208 // You probably don't want to use this one. See the
1209 // next three functions instead.
1210 pub fn new_block(cx: @mut FunctionContext,
1211 parent: Option<@mut Block>,
1212 scope: Option<@mut ScopeInfo>,
1215 opt_node_info: Option<NodeInfo>)
1218 let llbb = do name.with_c_str |buf| {
1219 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1221 let bcx = @mut Block::new(llbb,
1227 for cx in parent.iter() {
1237 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1238 node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1246 node_info: node_info,
1250 // Use this when you're at the top block of a function or the like.
1251 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1253 return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1254 "function top level", opt_node_info);
1257 pub fn scope_block(bcx: @mut Block,
1258 opt_node_info: Option<NodeInfo>,
1259 n: &str) -> @mut Block {
1260 return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1264 pub fn loop_scope_block(bcx: @mut Block,
1265 loop_break: @mut Block,
1266 loop_label: Option<Name>,
1268 opt_node_info: Option<NodeInfo>) -> @mut Block {
1269 return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1271 loop_break: Some(loop_break),
1272 loop_label: loop_label,
1276 node_info: opt_node_info,
1277 }), bcx.is_lpad, n, opt_node_info);
1280 // Use this when creating a block for the inside of a landing pad.
1281 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1282 new_block(bcx.fcx, Some(bcx), None, true, n, None)
1285 // Use this when you're making a general CFG BB within a scope.
1286 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1287 new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1290 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1291 @mut Block::new(llbb, None, is_lpad, None, fcx)
1295 // trans_block_cleanups: Go through all the cleanups attached to this
1296 // block and execute them.
1298 // When translating a block that introduces new variables during its scope, we
1299 // need to make sure those variables go out of scope when the block ends. We
1300 // do that by running a 'cleanup' function for each variable.
1301 // trans_block_cleanups runs all the cleanup functions for the block.
1302 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1303 trans_block_cleanups_(bcx, cleanups, false)
1306 pub fn trans_block_cleanups_(bcx: @mut Block,
1307 cleanups: &[cleanup],
1308 /* cleanup_cx: block, */
1309 is_lpad: bool) -> @mut Block {
1310 let _icx = push_ctxt("trans_block_cleanups");
1311 // NB: Don't short-circuit even if this block is unreachable because
1312 // GC-based cleanup needs to the see that the roots are live.
1314 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1315 if bcx.unreachable && !no_lpads { return bcx; }
1317 for cu in cleanups.rev_iter() {
1319 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1320 // Some types don't need to be cleaned up during
1321 // landing pads because they can be freed en mass later
1322 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1331 // In the last argument, Some(block) mean jump to this block, and none means
1332 // this is a landing pad and leaving should be accomplished with a resume
1334 pub fn cleanup_and_leave(bcx: @mut Block,
1335 upto: Option<BasicBlockRef>,
1336 leave: Option<BasicBlockRef>) {
1337 let _icx = push_ctxt("cleanup_and_leave");
1340 let is_lpad = leave == None;
1342 debug!("cleanup_and_leave: leaving %s", cur.to_str());
1344 if bcx.sess().trace() {
1347 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1350 let mut cur_scope = cur.scope;
1352 cur_scope = match cur_scope {
1353 Some (inf) if !inf.empty_cleanups() => {
1354 let (sub_cx, dest, inf_cleanups) = {
1355 let inf = &mut *inf;
1357 let mut dest = None;
1359 let r = (*inf).cleanup_paths.rev_iter().find(|cp| cp.target == leave);
1360 for cp in r.iter() {
1361 if cp.size == inf.cleanups.len() {
1367 dest = Some(cp.dest);
1370 let sub_cx = sub_block(bcx, "cleanup");
1371 Br(bcx, sub_cx.llbb);
1372 inf.cleanup_paths.push(cleanup_path {
1374 size: inf.cleanups.len(),
1377 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1379 bcx = trans_block_cleanups_(sub_cx,
1382 for &dest in dest.iter() {
1388 Some(inf) => inf.parent,
1394 Some(bb) => { if cur.llbb == bb { break; } }
1397 cur = match cur.parent {
1399 None => { assert!(upto.is_none()); break; }
1403 Some(target) => Br(bcx, target),
1404 None => { Resume(bcx, Load(bcx, bcx.fcx.personality.unwrap())); }
1408 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1409 let _icx = push_ctxt("cleanup_block");
1413 debug!("cleanup_block: %s", cur.to_str());
1415 if bcx.sess().trace() {
1418 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1421 let mut cur_scope = cur.scope;
1423 cur_scope = match cur_scope {
1425 bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1433 Some(bb) => { if cur.llbb == bb { break; } }
1436 cur = match cur.parent {
1438 None => { assert!(upto.is_none()); break; }
1444 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1445 let _icx = push_ctxt("cleanup_and_Br");
1446 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1449 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1450 let _icx = push_ctxt("leave_block");
1451 let next_cx = sub_block(block_parent(out_of), "next");
1452 if bcx.unreachable { Unreachable(next_cx); }
1453 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1457 pub fn with_scope(bcx: @mut Block,
1458 opt_node_info: Option<NodeInfo>,
1460 f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1461 let _icx = push_ctxt("with_scope");
1463 debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1464 bcx.to_str(), opt_node_info, name);
1465 let _indenter = indenter();
1467 let scope = simple_block_scope(bcx.scope, opt_node_info);
1468 bcx.scope = Some(scope);
1470 let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1471 bcx.scope = scope.parent;
1475 pub fn with_scope_result(bcx: @mut Block,
1476 opt_node_info: Option<NodeInfo>,
1478 f: &fn(@mut Block) -> Result) -> Result {
1479 let _icx = push_ctxt("with_scope_result");
1481 let scope = simple_block_scope(bcx.scope, opt_node_info);
1482 bcx.scope = Some(scope);
1483 let Result { bcx: out_bcx, val } = f(bcx);
1484 let out_bcx = trans_block_cleanups_(out_bcx,
1485 (scope.cleanups).clone(),
1487 bcx.scope = scope.parent;
1492 pub fn with_scope_datumblock(bcx: @mut Block, opt_node_info: Option<NodeInfo>,
1493 name: &str, f: &fn(@mut Block) -> datum::DatumBlock)
1494 -> datum::DatumBlock {
1495 use middle::trans::datum::DatumBlock;
1497 let _icx = push_ctxt("with_scope_result");
1498 let scope_cx = scope_block(bcx, opt_node_info, name);
1499 Br(bcx, scope_cx.llbb);
1500 let DatumBlock {bcx, datum} = f(scope_cx);
1501 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1504 pub fn block_locals(b: &ast::Block, it: &fn(@ast::Local)) {
1505 for s in b.stmts.iter() {
1507 ast::StmtDecl(d, _) => {
1509 ast::DeclLocal(ref local) => it(*local),
1510 _ => {} /* fall through */
1513 _ => {} /* fall through */
1518 pub fn with_cond(bcx: @mut Block, val: ValueRef, f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1519 let _icx = push_ctxt("with_cond");
1520 let next_cx = base::sub_block(bcx, "next");
1521 let cond_cx = base::sub_block(bcx, "cond");
1522 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1523 let after_cx = f(cond_cx);
1524 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1528 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1529 let _icx = push_ctxt("call_memcpy");
1531 let key = match ccx.sess.targ_cfg.arch {
1532 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1533 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1535 let memcpy = ccx.intrinsics.get_copy(&key);
1536 let src_ptr = PointerCast(cx, src, Type::i8p());
1537 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1538 let size = IntCast(cx, n_bytes, ccx.int_type);
1539 let align = C_i32(align as i32);
1540 let volatile = C_i1(false);
1541 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1544 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1545 let _icx = push_ctxt("memcpy_ty");
1546 let ccx = bcx.ccx();
1547 if ty::type_is_structural(t) {
1548 let llty = type_of::type_of(ccx, t);
1549 let llsz = llsize_of(ccx, llty);
1550 let llalign = llalign_of_min(ccx, llty);
1551 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1553 Store(bcx, Load(bcx, src), dst);
1557 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1558 if cx.unreachable { return; }
1559 let _icx = push_ctxt("zero_mem");
1562 let llty = type_of::type_of(ccx, t);
1563 memzero(&B(bcx), llptr, llty);
1566 // Always use this function instead of storing a zero constant to the memory
1567 // in question. If you store a zero constant, LLVM will drown in vreg
1568 // allocation for large data structures, and the generated code will be
1569 // awful. (A telltale sign of this is large quantities of
1570 // `mov [byte ptr foo],0` in the generated code.)
1571 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1572 let _icx = push_ctxt("memzero");
1575 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1576 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1577 X86_64 => "llvm.memset.p0i8.i64"
1580 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1581 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1582 let llzeroval = C_u8(0);
1583 let size = machine::llsize_of(ccx, ty);
1584 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1585 let volatile = C_i1(false);
1586 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1589 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1590 let _icx = push_ctxt("alloc_ty");
1591 let ccx = bcx.ccx();
1592 let ty = type_of::type_of(ccx, t);
1593 assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1594 let val = alloca(bcx, ty, name);
1598 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1599 alloca_maybe_zeroed(cx, ty, name, false)
1602 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1603 let _icx = push_ctxt("alloca");
1606 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1609 let p = Alloca(cx, ty, name);
1611 let b = cx.fcx.ccx.builder();
1612 b.position_before(cx.fcx.alloca_insert_pt.unwrap());
1618 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1619 let _icx = push_ctxt("arrayalloca");
1622 return llvm::LLVMGetUndef(ty.to_ref());
1625 return ArrayAlloca(cx, ty, v);
1628 pub struct BasicBlocks {
1632 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1634 let cx = task_llcx();
1635 do "static_allocas".with_c_str | buf| {
1636 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1641 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1643 let cx = task_llcx();
1644 do "return".with_c_str |buf| {
1645 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1650 // Creates and returns space for, or returns the argument representing, the
1651 // slot where the return value of the function must go.
1652 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1654 if type_of::return_uses_outptr(fcx.ccx.tcx, output_type) {
1655 llvm::LLVMGetParam(fcx.llfn, 0)
1657 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1658 let bcx = fcx.entry_bcx.unwrap();
1659 Alloca(bcx, lloutputtype, "__make_return_pointer")
1664 // NB: must keep 4 fns in sync:
1667 // - create_llargs_for_fn_args.
1670 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1676 param_substs: Option<@param_substs>,
1677 opt_node_info: Option<NodeInfo>,
1679 -> @mut FunctionContext {
1680 for p in param_substs.iter() { p.validate(); }
1682 debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1684 path_str(ccx.sess, path),
1686 param_substs.repr(ccx.tcx));
1688 let substd_output_type = match param_substs {
1689 None => output_type,
1691 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1694 let uses_outptr = type_of::return_uses_outptr(ccx.tcx, substd_output_type);
1695 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1697 let fcx = @mut FunctionContext {
1700 llvm::LLVMGetUndef(Type::i8p().to_ref())
1704 alloca_insert_pt: None,
1708 caller_expects_out_pointer: uses_outptr,
1709 llargs: @mut HashMap::new(),
1710 lllocals: @mut HashMap::new(),
1711 llupvars: @mut HashMap::new(),
1713 param_substs: param_substs,
1717 debug_context: debug_context,
1719 fcx.llenv = unsafe {
1720 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1724 let entry_bcx = top_scope_block(fcx, opt_node_info);
1725 Load(entry_bcx, C_null(Type::i8p()));
1727 fcx.entry_bcx = Some(entry_bcx);
1728 fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1731 if !ty::type_is_voidish(substd_output_type) {
1732 // If the function returns nil/bot, there is no real return
1733 // value, so do not set `llretptr`.
1734 if !skip_retptr || uses_outptr {
1735 // Otherwise, we normally allocate the llretptr, unless we
1736 // have been instructed to skip it for immediate return
1738 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1744 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1749 -> @mut FunctionContext {
1750 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1753 // NB: must keep 4 fns in sync:
1756 // - create_llargs_for_fn_args.
1760 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1761 // allocas created for them.
1763 // When we translate a function, we need to map its incoming arguments to the
1764 // spaces that have been created for them (by code in the llallocas field of
1765 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1766 // field of the fn_ctxt with
1767 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1771 let _icx = push_ctxt("create_llargs_for_fn_args");
1774 impl_self(tt, self_mode) => {
1775 cx.llself = Some(ValSelfData {
1778 is_copy: self_mode == ty::ByCopy
1784 // Return an array containing the ValueRefs that we get from
1785 // llvm::LLVMGetParam for each argument.
1786 do vec::from_fn(args.len()) |i| {
1787 unsafe { llvm::LLVMGetParam(cx.llfn, cx.arg_pos(i) as c_uint) }
1791 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1794 raw_llargs: &[ValueRef],
1795 arg_tys: &[ty::t]) -> @mut Block {
1796 debug!("copy_args_to_allocas: raw_llargs=%s arg_tys=%s",
1797 raw_llargs.llrepr(fcx.ccx),
1798 arg_tys.repr(fcx.ccx.tcx));
1800 let _icx = push_ctxt("copy_args_to_allocas");
1805 let self_val = if slf.is_copy
1806 && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1807 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1808 let alloc = alloc_ty(bcx, slf.t, "__self");
1809 Store(bcx, tmp, alloc);
1812 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1815 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1816 add_clean(bcx, self_val, slf.t);
1818 if fcx.ccx.sess.opts.extra_debuginfo {
1819 debuginfo::create_self_argument_metadata(bcx, slf.t, self_val);
1825 for (arg_n, &arg_ty) in arg_tys.iter().enumerate() {
1826 let raw_llarg = raw_llargs[arg_n];
1828 // For certain mode/type combinations, the raw llarg values are passed
1829 // by value. However, within the fn body itself, we want to always
1830 // have all locals and arguments be by-ref so that we can cancel the
1831 // cleanup and for better interaction with LLVM's debug info. So, if
1832 // the argument would be passed by value, we store it into an alloca.
1833 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1834 // the event it's not truly needed.
1835 // only by value if immediate:
1836 let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1837 let alloc = alloc_ty(bcx, arg_ty, "__arg");
1838 Store(bcx, raw_llarg, alloc);
1843 bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1845 if fcx.ccx.sess.opts.extra_debuginfo {
1846 debuginfo::create_argument_metadata(bcx, &args[arg_n]);
1853 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1854 // and builds the return block.
1855 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1856 let _icx = push_ctxt("finish_fn");
1858 let ret_cx = match fcx.llreturn {
1860 if !last_bcx.terminated {
1861 Br(last_bcx, llreturn);
1863 raw_block(fcx, false, llreturn)
1867 build_return_block(fcx, ret_cx);
1871 // Builds the return block for a function.
1872 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1873 // Return the value if this function immediate; otherwise, return void.
1874 if fcx.llretptr.is_none() || fcx.caller_expects_out_pointer {
1875 return RetVoid(ret_cx);
1878 let retptr = Value(fcx.llretptr.unwrap());
1879 let retval = match retptr.get_dominating_store(ret_cx) {
1880 // If there's only a single store to the ret slot, we can directly return
1881 // the value that was stored and omit the store and the alloca
1883 let retval = *s.get_operand(0).unwrap();
1884 s.erase_from_parent();
1886 if retptr.has_no_uses() {
1887 retptr.erase_from_parent();
1892 // Otherwise, load the return value from the ret slot
1893 None => Load(ret_cx, fcx.llretptr.unwrap())
1897 Ret(ret_cx, retval);
1900 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1902 // trans_closure: Builds an LLVM function out of a source function.
1903 // If the function closes over its environment a closure will be
1905 pub fn trans_closure(ccx: @mut CrateContext,
1907 decl: &ast::fn_decl,
1911 param_substs: Option<@param_substs>,
1913 attributes: &[ast::Attribute],
1915 maybe_load_env: &fn(@mut FunctionContext)) {
1916 ccx.stats.n_closures += 1;
1917 let _icx = push_ctxt("trans_closure");
1918 set_uwtable(llfndecl);
1920 debug!("trans_closure(..., param_substs=%s)",
1921 param_substs.repr(ccx.tcx));
1923 let fcx = new_fn_ctxt_w_id(ccx,
1933 // Create the first basic block in the function and keep a handle on it to
1934 // pass to finish_fn later.
1935 let bcx_top = fcx.entry_bcx.unwrap();
1936 let mut bcx = bcx_top;
1937 let block_ty = node_id_type(bcx, body.id);
1939 // Set up arguments to the function.
1940 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1941 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1943 // Set the fixed stack segment flag if necessary.
1944 if attr::contains_name(attributes, "fixed_stack_segment") {
1945 set_no_inline(fcx.llfn);
1946 set_fixed_stack_segment(fcx.llfn);
1949 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1951 maybe_load_env(fcx);
1953 // Up until here, IR instructions for this function have explicitly not been annotated with
1954 // source code location, so we don't step into call setup code. From here on, source location
1955 // emitting should be enabled.
1956 debuginfo::start_emitting_source_locations(fcx);
1958 // This call to trans_block is the place where we bridge between
1959 // translation calls that don't have a return value (trans_crate,
1960 // trans_mod, trans_item, et cetera) and those that do
1961 // (trans_block, trans_expr, et cetera).
1962 if body.expr.is_none() || ty::type_is_voidish(block_ty) {
1963 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1965 let dest = expr::SaveIn(fcx.llretptr.unwrap());
1966 bcx = controlflow::trans_block(bcx, body, dest);
1969 match fcx.llreturn {
1970 Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1971 None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1974 // Put return block after all other blocks.
1975 // This somewhat improves single-stepping experience in debugger.
1977 for &llreturn in fcx.llreturn.iter() {
1978 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1982 // Insert the mandatory first few basic blocks before lltop.
1983 finish_fn(fcx, bcx);
1986 // trans_fn: creates an LLVM function corresponding to a source language
1988 pub fn trans_fn(ccx: @mut CrateContext,
1990 decl: &ast::fn_decl,
1994 param_substs: Option<@param_substs>,
1996 attrs: &[ast::Attribute]) {
1998 let the_path_str = path_str(ccx.sess, path);
1999 let _s = StatRecorder::new(ccx, the_path_str);
2000 debug!("trans_fn(self_arg=%?, param_substs=%s)",
2002 param_substs.repr(ccx.tcx));
2003 let _icx = push_ctxt("trans_fn");
2004 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
2018 fn insert_synthetic_type_entries(bcx: @mut Block,
2019 fn_args: &[ast::arg],
2023 * For tuple-like structs and enum-variants, we generate
2024 * synthetic AST nodes for the arguments. These have no types
2025 * in the type table and no entries in the moves table,
2026 * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
2027 * gets upset. This hack of a function bridges the gap by inserting types.
2029 * This feels horrible. I think we should just have a special path
2030 * for these functions and not try to use the generic code, but
2031 * that's not the problem I'm trying to solve right now. - nmatsakis
2034 let tcx = bcx.tcx();
2035 for i in range(0u, fn_args.len()) {
2036 debug!("setting type of argument %u (pat node %d) to %s",
2037 i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
2039 let pat_id = fn_args[i].pat.id;
2040 let arg_ty = arg_tys[i];
2041 tcx.node_types.insert(pat_id as uint, arg_ty);
2045 pub fn trans_enum_variant(ccx: @mut CrateContext,
2046 _enum_id: ast::NodeId,
2047 variant: &ast::variant,
2048 args: &[ast::variant_arg],
2050 param_substs: Option<@param_substs>,
2051 llfndecl: ValueRef) {
2052 let _icx = push_ctxt("trans_enum_variant");
2054 trans_enum_variant_or_tuple_like_struct(
2063 pub fn trans_tuple_struct(ccx: @mut CrateContext,
2064 fields: &[@ast::struct_field],
2065 ctor_id: ast::NodeId,
2066 param_substs: Option<@param_substs>,
2067 llfndecl: ValueRef) {
2068 let _icx = push_ctxt("trans_tuple_struct");
2070 trans_enum_variant_or_tuple_like_struct(
2080 fn id(&self) -> ast::NodeId;
2081 fn ty<'a>(&'a self) -> &'a ast::Ty;
2084 impl IdAndTy for ast::variant_arg {
2085 fn id(&self) -> ast::NodeId { self.id }
2086 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
2089 impl IdAndTy for @ast::struct_field {
2090 fn id(&self) -> ast::NodeId { self.node.id }
2091 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
2094 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2095 ccx: @mut CrateContext,
2096 ctor_id: ast::NodeId,
2099 param_substs: Option<@param_substs>,
2102 // Translate variant arguments to function arguments.
2103 let fn_args = do args.map |varg| {
2106 ty: (*varg.ty()).clone(),
2107 pat: ast_util::ident_to_pat(
2108 ccx.tcx.sess.next_node_id(),
2109 codemap::dummy_sp(),
2110 special_idents::arg),
2115 let no_substs: &[ty::t] = [];
2116 let ty_param_substs = match param_substs {
2117 Some(ref substs) => {
2118 let v: &[ty::t] = substs.tys;
2122 let v: &[ty::t] = no_substs;
2127 let ctor_ty = ty::subst_tps(ccx.tcx,
2130 ty::node_id_to_type(ccx.tcx, ctor_id));
2132 let result_ty = match ty::get(ctor_ty).sty {
2133 ty::ty_bare_fn(ref bft) => bft.sig.output,
2135 fmt!("trans_enum_variant_or_tuple_like_struct: \
2136 unexpected ctor return type %s",
2137 ty_to_str(ccx.tcx, ctor_ty)))
2140 let fcx = new_fn_ctxt_w_id(ccx,
2150 let arg_tys = ty::ty_fn_args(ctor_ty);
2152 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2154 let bcx = fcx.entry_bcx.unwrap();
2156 insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2157 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2159 let repr = adt::represent_type(ccx, result_ty);
2160 adt::trans_start_init(bcx, repr, fcx.llretptr.unwrap(), disr);
2161 for (i, fn_arg) in fn_args.iter().enumerate() {
2162 let lldestptr = adt::trans_field_ptr(bcx,
2164 fcx.llretptr.unwrap(),
2167 let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2168 let arg_ty = arg_tys[i];
2169 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2171 finish_fn(fcx, bcx);
2174 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2175 id: ast::NodeId, vi: @~[@ty::VariantInfo],
2177 for variant in enum_definition.variants.iter() {
2178 let disr_val = vi[*i].disr_val;
2181 match variant.node.kind {
2182 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2183 let llfn = get_item_val(ccx, variant.node.id);
2184 trans_enum_variant(ccx, id, variant, *args,
2185 disr_val, None, llfn);
2187 ast::tuple_variant_kind(_) => {
2190 ast::struct_variant_kind(struct_def) => {
2191 trans_struct_def(ccx, struct_def);
2197 pub struct TransItemVisitor;
2199 impl Visitor<@mut CrateContext> for TransItemVisitor {
2200 fn visit_item(&mut self, i: @ast::item, ccx: @mut CrateContext) {
2205 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2206 let _icx = push_ctxt("trans_item");
2207 let path = match ccx.tcx.items.get_copy(&item.id) {
2208 ast_map::node_item(_, p) => p,
2210 _ => fail!("trans_item"),
2213 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2214 if purity == ast::extern_fn {
2215 let llfndecl = get_item_val(ccx, item.id);
2216 foreign::trans_rust_fn_with_foreign_abi(
2218 &vec::append((*path).clone(),
2219 [path_name(item.ident)]),
2224 } else if !generics.is_type_parameterized() {
2225 let llfndecl = get_item_val(ccx, item.id);
2227 vec::append((*path).clone(), [path_name(item.ident)]),
2236 // Be sure to travel more than just one layer deep to catch nested
2237 // items in blocks and such.
2238 let mut v = TransItemVisitor;
2239 v.visit_block(body, ccx);
2242 ast::item_impl(ref generics, _, _, ref ms) => {
2243 meth::trans_impl(ccx,
2250 ast::item_mod(ref m) => {
2253 ast::item_enum(ref enum_definition, ref generics) => {
2254 if !generics.is_type_parameterized() {
2255 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2257 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2260 ast::item_static(_, m, expr) => {
2261 consts::trans_const(ccx, m, item.id);
2262 // Do static_assert checking. It can't really be done much earlier
2263 // because we need to get the value of the bool out of LLVM
2264 if attr::contains_name(item.attrs, "static_assert") {
2265 if m == ast::MutMutable {
2266 ccx.sess.span_fatal(expr.span,
2267 "cannot have static_assert on a mutable \
2270 let v = ccx.const_values.get_copy(&item.id);
2272 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2273 ccx.sess.span_fatal(expr.span, "static assertion failed");
2278 ast::item_foreign_mod(ref foreign_mod) => {
2279 foreign::trans_foreign_mod(ccx, foreign_mod);
2281 ast::item_struct(struct_def, ref generics) => {
2282 if !generics.is_type_parameterized() {
2283 trans_struct_def(ccx, struct_def);
2286 ast::item_trait(*) => {
2287 // Inside of this trait definition, we won't be actually translating any
2288 // functions, but the trait still needs to be walked. Otherwise default
2289 // methods with items will not get translated and will cause ICE's when
2290 // metadata time comes around.
2291 let mut v = TransItemVisitor;
2292 visit::walk_item(&mut v, item, ccx);
2294 _ => {/* fall through */ }
2298 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2299 // If this is a tuple-like struct, translate the constructor.
2300 match struct_def.ctor_id {
2301 // We only need to translate a constructor if there are fields;
2302 // otherwise this is a unit-like struct.
2303 Some(ctor_id) if struct_def.fields.len() > 0 => {
2304 let llfndecl = get_item_val(ccx, ctor_id);
2305 trans_tuple_struct(ccx, struct_def.fields,
2306 ctor_id, None, llfndecl);
2308 Some(_) | None => {}
2312 // Translate a module. Doing this amounts to translating the items in the
2313 // module; there ends up being no artifact (aside from linkage names) of
2314 // separate modules in the compiled program. That's because modules exist
2315 // only as a convenience for humans working with the code, to organize names
2316 // and control visibility.
2317 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2318 let _icx = push_ctxt("trans_mod");
2319 for item in m.items.iter() {
2320 trans_item(ccx, *item);
2324 pub fn register_fn(ccx: @mut CrateContext,
2327 node_id: ast::NodeId,
2330 let f = match ty::get(node_type).sty {
2331 ty::ty_bare_fn(ref f) => {
2332 assert!(f.abis.is_rust() || f.abis.is_intrinsic());
2335 _ => fail!("expected bare rust fn or an intrinsic")
2338 let llfn = decl_rust_fn(ccx, f.sig.inputs, f.sig.output, sym);
2339 ccx.item_symbols.insert(node_id, sym);
2341 // FIXME #4404 android JNI hacks
2342 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2343 (*ccx.sess.building_library &&
2344 ccx.sess.targ_cfg.os == session::OsAndroid));
2346 create_entry_wrapper(ccx, sp, llfn);
2351 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2352 pub fn register_fn_llvmty(ccx: @mut CrateContext,
2355 node_id: ast::NodeId,
2356 cc: lib::llvm::CallConv,
2359 debug!("register_fn_fuller creating fn for item %d with path %s",
2361 ast_map::path_to_str(item_path(ccx, &node_id), token::get_ident_interner()));
2363 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty);
2364 ccx.item_symbols.insert(node_id, sym);
2366 // FIXME #4404 android JNI hacks
2367 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2368 (*ccx.sess.building_library &&
2369 ccx.sess.targ_cfg.os == session::OsAndroid));
2371 create_entry_wrapper(ccx, sp, llfn);
2376 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2377 match *sess.entry_fn {
2378 Some((entry_id, _)) => node_id == entry_id,
2383 // Create a _rust_main(args: ~[str]) function which will be called from the
2384 // runtime rust_start function
2385 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2387 main_llfn: ValueRef) {
2388 let et = ccx.sess.entry_type.unwrap();
2390 session::EntryMain => {
2391 let llfn = create_main(ccx, main_llfn);
2392 create_entry_fn(ccx, llfn, true);
2394 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
2395 session::EntryNone => {} // Do nothing.
2398 fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2399 let nt = ty::mk_nil();
2400 let llfty = type_of_rust_fn(ccx, [], nt);
2401 let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2402 lib::llvm::CCallConv, llfty);
2404 let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2406 // the args vector built in create_entry_fn will need
2407 // be updated if this assertion starts to fail.
2408 assert!(!fcx.caller_expects_out_pointer);
2410 let bcx = fcx.entry_bcx.unwrap();
2412 let llenvarg = unsafe {
2413 let env_arg = fcx.env_arg_pos();
2414 llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2416 let args = ~[llenvarg];
2417 Call(bcx, main_llfn, args, []);
2419 finish_fn(fcx, bcx);
2423 fn create_entry_fn(ccx: @mut CrateContext,
2424 rust_main: ValueRef,
2425 use_start_lang_item: bool) {
2426 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2429 // FIXME #4404 android JNI hacks
2430 let main_name = if *ccx.sess.building_library {
2435 let llfn = decl_cdecl_fn(ccx.llmod, main_name, llfty);
2436 let llbb = do "top".with_c_str |buf| {
2438 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2441 let bld = ccx.builder.B;
2443 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2445 let crate_map = ccx.crate_map;
2446 let opaque_crate_map = do "crate_map".with_c_str |buf| {
2447 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2450 let (start_fn, args) = if use_start_lang_item {
2451 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2453 Err(s) => { ccx.tcx.sess.fatal(s); }
2455 let start_fn = if start_def_id.crate == ast::LOCAL_CRATE {
2456 get_item_val(ccx, start_def_id.node)
2458 let start_fn_type = csearch::get_type(ccx.tcx,
2460 trans_external_path(ccx, start_def_id, start_fn_type)
2464 let opaque_rust_main = do "rust_main".with_c_str |buf| {
2465 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2469 C_null(Type::opaque_box(ccx).ptr_to()),
2471 llvm::LLVMGetParam(llfn, 0),
2472 llvm::LLVMGetParam(llfn, 1),
2478 debug!("using user-defined start fn");
2480 C_null(Type::opaque_box(ccx).ptr_to()),
2481 llvm::LLVMGetParam(llfn, 0 as c_uint),
2482 llvm::LLVMGetParam(llfn, 1 as c_uint),
2489 let result = do args.as_imm_buf |buf, len| {
2490 llvm::LLVMBuildCall(bld, start_fn, buf, len as c_uint, noname())
2493 llvm::LLVMBuildRet(bld, result);
2498 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2499 llenvptr: ValueRef) {
2500 let ccx = bcx.ccx();
2501 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2502 Store(bcx, llfn, code_cell);
2503 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2504 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2505 Store(bcx, llenvblobptr, env_cell);
2508 pub fn item_path(ccx: &CrateContext, id: &ast::NodeId) -> path {
2509 ty::item_path(ccx.tcx, ast_util::local_def(*id))
2512 fn exported_name(ccx: @mut CrateContext, path: path, ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
2513 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2514 // Use provided name
2515 Some(name) => name.to_owned(),
2518 _ if attr::contains_name(attrs, "no_mangle")
2519 => path_elt_to_str(*path.last(), token::get_ident_interner()),
2521 // Usual name mangling
2522 _ => mangle_exported_name(ccx, path, ty)
2526 pub fn get_item_val(ccx: @mut CrateContext, id: ast::NodeId) -> ValueRef {
2527 debug!("get_item_val(id=`%?`)", id);
2529 let val = ccx.item_vals.find_copy(&id);
2533 let mut exprt = false;
2534 let item = ccx.tcx.items.get_copy(&id);
2535 let val = match item {
2536 ast_map::node_item(i, pth) => {
2538 let elt = path_pretty_name(i.ident, id as u64);
2539 let my_path = vec::append_one((*pth).clone(), elt);
2540 let ty = ty::node_id_to_type(ccx.tcx, i.id);
2541 let sym = exported_name(ccx, my_path, ty, i.attrs);
2543 let v = match i.node {
2544 ast::item_static(_, _, expr) => {
2545 // If this static came from an external crate, then
2546 // we need to get the symbol from csearch instead of
2547 // using the current crate's name/version
2548 // information in the hash of the symbol
2549 debug!("making %s", sym);
2550 let sym = match ccx.external_srcs.find(&i.id) {
2552 debug!("but found in other crate...");
2553 csearch::get_symbol(ccx.sess.cstore, did)
2558 // We need the translated value here, because for enums the
2559 // LLVM type is not fully determined by the Rust type.
2560 let (v, inlineable) = consts::const_expr(ccx, expr);
2561 ccx.const_values.insert(id, v);
2563 debug!("%s not inlined", sym);
2564 ccx.non_inlineable_statics.insert(id);
2569 let llty = llvm::LLVMTypeOf(v);
2570 let g = do sym.with_c_str |buf| {
2571 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2574 // Apply the `unnamed_addr` attribute if
2576 if attr::contains_name(i.attrs,
2577 "address_insignificant"){
2578 lib::llvm::SetUnnamedAddr(g, true);
2579 lib::llvm::SetLinkage(g,
2580 lib::llvm::InternalLinkage);
2583 ccx.item_symbols.insert(i.id, sym);
2588 ast::item_fn(_, purity, _, _, _) => {
2589 let llfn = if purity != ast::extern_fn {
2590 register_fn(ccx, i.span, sym, i.id, ty)
2592 foreign::register_rust_fn_with_foreign_abi(ccx,
2597 set_llvm_fn_attrs(i.attrs, llfn);
2601 _ => fail!("get_item_val: weird result in table")
2604 match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2605 Some(sect) => unsafe {
2606 do sect.with_c_str |buf| {
2607 llvm::LLVMSetSection(v, buf);
2616 ast_map::node_trait_method(trait_method, _, pth) => {
2617 debug!("get_item_val(): processing a node_trait_method");
2618 match *trait_method {
2619 ast::required(_) => {
2620 ccx.sess.bug("unexpected variant: required trait method in \
2623 ast::provided(m) => {
2625 register_method(ccx, id, pth, m)
2630 ast_map::node_method(m, _, pth) => {
2631 register_method(ccx, id, pth, m)
2634 ast_map::node_foreign_item(ni, abis, _, pth) => {
2635 let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2639 ast::foreign_item_fn(*) => {
2640 let path = vec::append((*pth).clone(), [path_name(ni.ident)]);
2641 foreign::register_foreign_item_fn(ccx, abis, &path, ni)
2643 ast::foreign_item_static(*) => {
2644 let ident = token::ident_to_str(&ni.ident);
2645 let g = do ident.with_c_str |buf| {
2647 let ty = type_of(ccx, ty);
2648 llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2656 ast_map::node_variant(ref v, enm, pth) => {
2659 ast::tuple_variant_kind(ref args) => {
2660 assert!(args.len() != 0u);
2661 let pth = vec::append((*pth).clone(),
2662 [path_name(enm.ident),
2663 path_name((*v).node.name)]);
2664 let ty = ty::node_id_to_type(ccx.tcx, id);
2665 let sym = exported_name(ccx, pth, ty, enm.attrs);
2667 llfn = match enm.node {
2668 ast::item_enum(_, _) => {
2669 register_fn(ccx, (*v).span, sym, id, ty)
2671 _ => fail!("node_variant, shouldn't happen")
2674 ast::struct_variant_kind(_) => {
2675 fail!("struct variant kind unexpected in get_item_val")
2678 set_inline_hint(llfn);
2682 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2683 // Only register the constructor if this is a tuple-like struct.
2684 match struct_def.ctor_id {
2686 ccx.tcx.sess.bug("attempt to register a constructor of \
2687 a non-tuple-like struct")
2690 let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2691 let sym = exported_name(ccx, (*struct_path).clone(), ty,
2693 let llfn = register_fn(ccx, struct_item.span,
2695 set_inline_hint(llfn);
2702 ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2707 if !exprt && !ccx.reachable.contains(&id) {
2708 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2711 ccx.item_vals.insert(id, val);
2717 pub fn register_method(ccx: @mut CrateContext,
2719 path: @ast_map::path,
2720 m: @ast::method) -> ValueRef {
2721 let mty = ty::node_id_to_type(ccx.tcx, id);
2723 let mut path = (*path).clone();
2724 path.push(path_pretty_name(m.ident, token::gensym("meth") as u64));
2726 let sym = exported_name(ccx, path, mty, m.attrs);
2728 let llfn = register_fn(ccx, m.span, sym, id, mty);
2729 set_llvm_fn_attrs(m.attrs, llfn);
2733 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2735 return PtrToInt(cx, v, ccx.int_type);
2738 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2740 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2745 ($intrinsics:ident, $name:expr, $args:expr, $ret:expr) => ({
2747 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2748 $intrinsics.insert(name, f);
2752 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2753 let i8p = Type::i8p();
2754 let mut intrinsics = HashMap::new();
2756 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i32",
2757 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2758 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i64",
2759 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2760 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i32",
2761 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2762 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i64",
2763 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2764 ifn!(intrinsics, "llvm.memset.p0i8.i32",
2765 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2766 ifn!(intrinsics, "llvm.memset.p0i8.i64",
2767 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2769 ifn!(intrinsics, "llvm.trap", [], Type::void());
2770 ifn!(intrinsics, "llvm.frameaddress", [Type::i32()], i8p);
2772 ifn!(intrinsics, "llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2773 ifn!(intrinsics, "llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2774 ifn!(intrinsics, "llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2775 ifn!(intrinsics, "llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2777 ifn!(intrinsics, "llvm.sqrt.f32", [Type::f32()], Type::f32());
2778 ifn!(intrinsics, "llvm.sqrt.f64", [Type::f64()], Type::f64());
2779 ifn!(intrinsics, "llvm.sin.f32", [Type::f32()], Type::f32());
2780 ifn!(intrinsics, "llvm.sin.f64", [Type::f64()], Type::f64());
2781 ifn!(intrinsics, "llvm.cos.f32", [Type::f32()], Type::f32());
2782 ifn!(intrinsics, "llvm.cos.f64", [Type::f64()], Type::f64());
2783 ifn!(intrinsics, "llvm.exp.f32", [Type::f32()], Type::f32());
2784 ifn!(intrinsics, "llvm.exp.f64", [Type::f64()], Type::f64());
2785 ifn!(intrinsics, "llvm.exp2.f32", [Type::f32()], Type::f32());
2786 ifn!(intrinsics, "llvm.exp2.f64", [Type::f64()], Type::f64());
2787 ifn!(intrinsics, "llvm.log.f32", [Type::f32()], Type::f32());
2788 ifn!(intrinsics, "llvm.log.f64", [Type::f64()], Type::f64());
2789 ifn!(intrinsics, "llvm.log10.f32",[Type::f32()], Type::f32());
2790 ifn!(intrinsics, "llvm.log10.f64",[Type::f64()], Type::f64());
2791 ifn!(intrinsics, "llvm.log2.f32", [Type::f32()], Type::f32());
2792 ifn!(intrinsics, "llvm.log2.f64", [Type::f64()], Type::f64());
2794 ifn!(intrinsics, "llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2795 ifn!(intrinsics, "llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2797 ifn!(intrinsics, "llvm.fabs.f32", [Type::f32()], Type::f32());
2798 ifn!(intrinsics, "llvm.fabs.f64", [Type::f64()], Type::f64());
2799 ifn!(intrinsics, "llvm.floor.f32",[Type::f32()], Type::f32());
2800 ifn!(intrinsics, "llvm.floor.f64",[Type::f64()], Type::f64());
2801 ifn!(intrinsics, "llvm.ceil.f32", [Type::f32()], Type::f32());
2802 ifn!(intrinsics, "llvm.ceil.f64", [Type::f64()], Type::f64());
2803 ifn!(intrinsics, "llvm.trunc.f32",[Type::f32()], Type::f32());
2804 ifn!(intrinsics, "llvm.trunc.f64",[Type::f64()], Type::f64());
2806 ifn!(intrinsics, "llvm.ctpop.i8", [Type::i8()], Type::i8());
2807 ifn!(intrinsics, "llvm.ctpop.i16",[Type::i16()], Type::i16());
2808 ifn!(intrinsics, "llvm.ctpop.i32",[Type::i32()], Type::i32());
2809 ifn!(intrinsics, "llvm.ctpop.i64",[Type::i64()], Type::i64());
2811 ifn!(intrinsics, "llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2812 ifn!(intrinsics, "llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2813 ifn!(intrinsics, "llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2814 ifn!(intrinsics, "llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2816 ifn!(intrinsics, "llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2817 ifn!(intrinsics, "llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2818 ifn!(intrinsics, "llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2819 ifn!(intrinsics, "llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2821 ifn!(intrinsics, "llvm.bswap.i16",[Type::i16()], Type::i16());
2822 ifn!(intrinsics, "llvm.bswap.i32",[Type::i32()], Type::i32());
2823 ifn!(intrinsics, "llvm.bswap.i64",[Type::i64()], Type::i64());
2825 ifn!(intrinsics, "llvm.sadd.with.overflow.i8",
2826 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2827 ifn!(intrinsics, "llvm.sadd.with.overflow.i16",
2828 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2829 ifn!(intrinsics, "llvm.sadd.with.overflow.i32",
2830 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2831 ifn!(intrinsics, "llvm.sadd.with.overflow.i64",
2832 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2834 ifn!(intrinsics, "llvm.uadd.with.overflow.i8",
2835 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2836 ifn!(intrinsics, "llvm.uadd.with.overflow.i16",
2837 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2838 ifn!(intrinsics, "llvm.uadd.with.overflow.i32",
2839 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2840 ifn!(intrinsics, "llvm.uadd.with.overflow.i64",
2841 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2843 ifn!(intrinsics, "llvm.ssub.with.overflow.i8",
2844 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2845 ifn!(intrinsics, "llvm.ssub.with.overflow.i16",
2846 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2847 ifn!(intrinsics, "llvm.ssub.with.overflow.i32",
2848 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2849 ifn!(intrinsics, "llvm.ssub.with.overflow.i64",
2850 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2852 ifn!(intrinsics, "llvm.usub.with.overflow.i8",
2853 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2854 ifn!(intrinsics, "llvm.usub.with.overflow.i16",
2855 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2856 ifn!(intrinsics, "llvm.usub.with.overflow.i32",
2857 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2858 ifn!(intrinsics, "llvm.usub.with.overflow.i64",
2859 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2861 ifn!(intrinsics, "llvm.smul.with.overflow.i8",
2862 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2863 ifn!(intrinsics, "llvm.smul.with.overflow.i16",
2864 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2865 ifn!(intrinsics, "llvm.smul.with.overflow.i32",
2866 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2867 ifn!(intrinsics, "llvm.smul.with.overflow.i64",
2868 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2870 ifn!(intrinsics, "llvm.umul.with.overflow.i8",
2871 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2872 ifn!(intrinsics, "llvm.umul.with.overflow.i16",
2873 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2874 ifn!(intrinsics, "llvm.umul.with.overflow.i32",
2875 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2876 ifn!(intrinsics, "llvm.umul.with.overflow.i64",
2877 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2882 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2883 ifn!(intrinsics, "llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2885 "llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2888 pub fn trap(bcx: @mut Block) {
2889 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2890 Some(&x) => { Call(bcx, x, [], []); },
2891 _ => bcx.sess().bug("unbound llvm.trap in trap")
2895 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2896 if !ccx.sess.opts.gc || !ccx.uses_gc {
2900 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2901 let gc_metadata = do gc_metadata_name.with_c_str |buf| {
2903 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2907 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2908 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2909 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2913 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2914 let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2915 let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2916 let map = do "_rust_mod_map".with_c_str |buf| {
2918 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2921 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2922 let mut elts: ~[ValueRef] = ~[];
2924 // This is not ideal, but the borrow checker doesn't
2925 // like the multiple borrows. At least, it doesn't
2926 // like them on the current snapshot. (2013-06-14)
2928 for (k, _) in ccx.module_data.iter() {
2929 keys.push(k.to_managed());
2932 for key in keys.iter() {
2933 let val = *ccx.module_data.find_equiv(key).unwrap();
2934 let s_const = C_cstr(ccx, *key);
2935 let s_ptr = p2i(ccx, s_const);
2936 let v_ptr = p2i(ccx, val);
2937 let elt = C_struct([s_ptr, v_ptr]);
2940 let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2943 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2949 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2950 llmod: ModuleRef) -> ValueRef {
2951 let targ_cfg = sess.targ_cfg;
2952 let int_type = Type::int(targ_cfg.arch);
2953 let mut n_subcrates = 1;
2954 let cstore = sess.cstore;
2955 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2956 let mapname = if *sess.building_library {
2957 fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2961 let sym_name = ~"_rust_crate_map_" + mapname;
2962 let arrtype = Type::array(&int_type, n_subcrates as u64);
2963 let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2964 let map = do sym_name.with_c_str |buf| {
2966 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2969 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2973 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2974 let mut subcrates: ~[ValueRef] = ~[];
2976 let cstore = ccx.sess.cstore;
2977 while cstore::have_crate_data(cstore, i) {
2978 let cdata = cstore::get_crate_data(cstore, i);
2979 let nm = fmt!("_rust_crate_map_%s_%s_%s",
2981 cstore::get_crate_vers(cstore, i),
2982 cstore::get_crate_hash(cstore, i));
2983 let cr = do nm.with_c_str |buf| {
2985 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2988 subcrates.push(p2i(ccx, cr));
2991 subcrates.push(C_int(ccx, 0));
2994 let mod_map = create_module_map(ccx);
2995 llvm::LLVMSetInitializer(map, C_struct(
2997 // FIXME #8431 This used to be the annihilate function, now it's nothing
2998 C_null(Type::i8p()),
3000 C_array(ccx.int_type, subcrates)]));
3004 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
3005 -> encoder::EncodeParams<'r> {
3007 let diag = cx.sess.diagnostic();
3008 let item_symbols = &cx.item_symbols;
3009 let discrim_symbols = &cx.discrim_symbols;
3010 let link_meta = &cx.link_meta;
3011 encoder::EncodeParams {
3014 reexports2: cx.exp_map2,
3015 item_symbols: item_symbols,
3016 discrim_symbols: discrim_symbols,
3017 non_inlineable_statics: &cx.non_inlineable_statics,
3018 link_meta: link_meta,
3019 cstore: cx.sess.cstore,
3020 encode_inlined_item: ie,
3021 reachable: cx.reachable,
3025 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) {
3026 if !*cx.sess.building_library { return; }
3028 let encode_inlined_item: encoder::encode_inlined_item =
3029 |ecx, ebml_w, path, ii|
3030 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
3032 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
3033 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
3034 let llconst = C_struct([llmeta]);
3035 let mut llglobal = do "rust_metadata".with_c_str |buf| {
3037 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
3041 llvm::LLVMSetInitializer(llglobal, llconst);
3042 do cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str |buf| {
3043 llvm::LLVMSetSection(llglobal, buf)
3045 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
3047 let t_ptr_i8 = Type::i8p();
3048 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
3049 let llvm_used = do "llvm.used".with_c_str |buf| {
3050 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
3052 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
3053 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
3057 fn mk_global(ccx: &CrateContext,
3063 let llglobal = do name.with_c_str |buf| {
3064 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
3066 llvm::LLVMSetInitializer(llglobal, llval);
3067 llvm::LLVMSetGlobalConstant(llglobal, True);
3070 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
3077 // Writes the current ABI version into the crate.
3078 pub fn write_abi_version(ccx: &mut CrateContext) {
3079 mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
3082 pub fn trans_crate(sess: session::Session,
3084 analysis: &CrateAnalysis,
3085 output: &Path) -> CrateTranslation {
3086 // Before we touch LLVM, make sure that multithreading is enabled.
3087 if unsafe { !llvm::LLVMRustStartMultithreading() } {
3088 //sess.bug("couldn't enable multi-threaded LLVM");
3091 let mut symbol_hasher = hash::default_state();
3092 let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
3094 // Append ".rc" to crate name as LLVM module identifier.
3096 // LLVM code generator emits a ".file filename" directive
3097 // for ELF backends. Value of the "filename" is set as the
3098 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
3099 // crashes if the module identifer is same as other symbols
3100 // such as a function name in the module.
3101 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
3102 let llmod_id = link_meta.name.to_owned() + ".rc";
3104 let ccx = @mut CrateContext::new(sess,
3111 analysis.reachable);
3113 if ccx.sess.opts.debuginfo {
3114 debuginfo::initialize(ccx, crate);
3118 let _icx = push_ctxt("text");
3119 trans_mod(ccx, &crate.module);
3122 decl_gc_metadata(ccx, llmod_id);
3123 fill_crate_map(ccx, ccx.crate_map);
3124 glue::emit_tydescs(ccx);
3125 write_abi_version(ccx);
3126 if ccx.sess.opts.debuginfo {
3127 debuginfo::finalize(ccx);
3130 // Translate the metadata.
3131 write_metadata(ccx, crate);
3132 if ccx.sess.trans_stats() {
3133 io::println("--- trans stats ---");
3134 printfln!("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
3135 printfln!("n_glues_created: %u", ccx.stats.n_glues_created);
3136 printfln!("n_null_glues: %u", ccx.stats.n_null_glues);
3137 printfln!("n_real_glues: %u", ccx.stats.n_real_glues);
3139 printfln!("n_fns: %u", ccx.stats.n_fns);
3140 printfln!("n_monos: %u", ccx.stats.n_monos);
3141 printfln!("n_inlines: %u", ccx.stats.n_inlines);
3142 printfln!("n_closures: %u", ccx.stats.n_closures);
3143 io::println("fn stats:");
3144 do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3147 for tuple in ccx.stats.fn_stats.iter() {
3149 (ref name, ms, insns) => {
3150 printfln!("%u insns, %u ms, %s", insns, ms, *name);
3155 if ccx.sess.count_llvm_insns() {
3156 for (k, v) in ccx.stats.llvm_insns.iter() {
3157 printfln!("%-7u %s", *v, *k);
3161 let llcx = ccx.llcx;
3162 let link_meta = ccx.link_meta;
3163 let llmod = ccx.llmod;
3165 return CrateTranslation {