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;
73 use std::libc::c_uint;
78 use syntax::ast::Name;
79 use syntax::ast_map::{path, path_elt_to_str, path_name, path_pretty_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;
87 use syntax::{ast, ast_util, codemap, ast_map};
88 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic, OsWin32, OsAndroid};
90 use syntax::visit::Visitor;
92 pub use middle::trans::context::task_llcx;
94 local_data_key!(task_local_insn_key: ~[&'static str])
96 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
97 do local_data::get(task_local_insn_key) |c| {
99 Some(ctx) => blk(*ctx),
105 pub fn init_insn_ctxt() {
106 local_data::set(task_local_insn_key, ~[]);
109 pub struct _InsnCtxt { _x: () }
112 impl Drop for _InsnCtxt {
114 do local_data::modify(task_local_insn_key) |c| {
123 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
124 debug!("new InsnCtxt: {}", s);
125 do local_data::modify(task_local_insn_key) |c| {
134 struct StatRecorder<'self> {
135 ccx: @mut CrateContext,
141 impl<'self> StatRecorder<'self> {
142 pub fn new(ccx: @mut CrateContext,
143 name: &'self str) -> StatRecorder<'self> {
144 let start = if ccx.sess.trans_stats() {
145 time::precise_time_ns()
149 let istart = ccx.stats.n_llvm_insns;
160 impl<'self> Drop for StatRecorder<'self> {
162 if self.ccx.sess.trans_stats() {
163 let end = time::precise_time_ns();
164 let elapsed = ((end - self.start) / 1_000_000) as uint;
165 let iend = self.ccx.stats.n_llvm_insns;
166 self.ccx.stats.fn_stats.push((self.name.to_owned(),
168 iend - self.istart));
169 self.ccx.stats.n_fns += 1;
170 // Reset LLVM insn count to avoid compound costs.
171 self.ccx.stats.n_llvm_insns = self.istart;
176 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
177 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
178 let llfn: ValueRef = do name.with_c_str |buf| {
180 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
184 lib::llvm::SetFunctionCallConv(llfn, cc);
185 // Function addresses in Rust are never significant, allowing functions to be merged.
186 lib::llvm::SetUnnamedAddr(llfn, true);
190 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
191 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
192 return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
195 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
196 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: &str,
197 cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
198 match externs.find_equiv(&name) {
199 Some(n) => return *n,
202 let f = decl_fn(llmod, name, cc, ty);
203 externs.insert(name.to_owned(), f);
207 fn get_extern_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t,
208 name: &str, did: ast::DefId) -> ValueRef {
209 match ccx.externs.find_equiv(&name) {
210 Some(n) => return *n,
213 let f = decl_rust_fn(ccx, inputs, output, name);
214 do csearch::get_item_attrs(ccx.tcx.cstore, did) |meta_items| {
215 set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).to_owned_vec(), f)
217 ccx.externs.insert(name.to_owned(), f);
221 fn decl_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t, name: &str) -> ValueRef {
222 let llfty = type_of_rust_fn(ccx, inputs, output);
223 let llfn = decl_cdecl_fn(ccx.llmod, name, llfty);
225 match ty::get(output).sty {
226 // functions returning bottom may unwind, but can never return normally
229 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
232 // `~` pointer return values never alias because ownership is transferred
234 ty::ty_evec(_, ty::vstore_uniq) => {
236 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
242 let uses_outptr = type_of::return_uses_outptr(ccx, output);
243 let offset = if uses_outptr { 2 } else { 1 };
245 for (i, &arg_ty) in inputs.iter().enumerate() {
246 let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
247 match ty::get(arg_ty).sty {
248 // `~` pointer parameters never alias because ownership is transferred
250 ty::ty_evec(_, ty::vstore_uniq) |
251 ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, _}) => {
253 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
260 // The out pointer will never alias with any other pointers, as the object only exists at a
261 // language level after the call. It can also be tagged with SRet to indicate that it is
262 // guaranteed to point to a usable block of memory for the type.
265 let outptr = llvm::LLVMGetParam(llfn, 0);
266 llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
267 llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
274 pub fn decl_internal_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t,
275 name: &str) -> ValueRef {
276 let llfn = decl_rust_fn(ccx, inputs, output, name);
277 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
281 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
282 name: &str, ty: Type) -> ValueRef {
283 match externs.find_equiv(&name) {
284 Some(n) => return *n,
288 let c = do name.with_c_str |buf| {
289 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
291 externs.insert(name.to_owned(), c);
296 // Returns a pointer to the body for the box. The box may be an opaque
297 // box. The result will be casted to the type of body_t, if it is statically
300 // The runtime equivalent is box_body() in "rust_internal.h".
301 pub fn opaque_box_body(bcx: @mut Block,
303 boxptr: ValueRef) -> ValueRef {
304 let _icx = push_ctxt("opaque_box_body");
306 let ty = type_of(ccx, body_t);
307 let ty = Type::box(ccx, &ty);
308 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
309 GEPi(bcx, boxptr, [0u, abi::box_field_body])
312 // malloc_raw_dyn: allocates a box to contain a given type, but with a
313 // potentially dynamic size.
314 pub fn malloc_raw_dyn(bcx: @mut Block,
317 size: ValueRef) -> Result {
318 let _icx = push_ctxt("malloc_raw");
321 fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::DefId {
322 let li = &bcx.tcx().lang_items;
323 match li.require(it) {
326 bcx.tcx().sess.fatal(format!("allocation of `{}` {}",
327 bcx.ty_to_str(t), s));
332 if heap == heap_exchange {
333 let llty_value = type_of::type_of(ccx, t);
337 let r = callee::trans_lang_call(
339 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
342 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
344 // we treat ~fn, @fn and @[] as @ here, which isn't ideal
345 let (mk_fn, langcall) = match heap {
346 heap_managed | heap_managed_unique => {
348 require_alloc_fn(bcx, t, MallocFnLangItem))
350 heap_exchange_closure => {
352 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
354 _ => fail!("heap_exchange already handled")
357 // Grab the TypeRef type of box_ptr_ty.
358 let box_ptr_ty = mk_fn(bcx.tcx(), t);
359 let llty = type_of(ccx, box_ptr_ty);
361 // Get the tydesc for the body:
362 let static_ti = get_tydesc(ccx, t);
363 glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
366 let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
367 let r = callee::trans_lang_call(
372 let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
373 maybe_set_managed_unique_rc(r.bcx, r.val, heap);
378 // malloc_raw: expects an unboxed type and returns a pointer to
379 // enough space for a box of that type. This includes a rust_opaque_box
381 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
382 let ty = type_of(bcx.ccx(), t);
383 let size = llsize_of(bcx.ccx(), ty);
384 malloc_raw_dyn(bcx, t, heap, size)
387 pub struct MallocResult {
393 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
394 // and pulls out the body
395 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
397 assert!(heap != heap_exchange);
398 let _icx = push_ctxt("malloc_general");
399 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
400 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
402 MallocResult { bcx: bcx, box: llbox, body: body }
405 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
406 let ty = type_of(bcx.ccx(), t);
407 assert!(heap != heap_exchange);
408 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
411 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
412 if ty::type_contents(bcx.tcx(), t).owns_managed() {
419 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
420 assert!(heap != heap_exchange);
421 if heap == heap_managed_unique {
422 // In cases where we are looking at a unique-typed allocation in the
423 // managed heap (thus have refcount 1 from the managed allocator),
424 // such as a ~(@foo) or such. These need to have their refcount forced
425 // to -2 so the annihilator ignores them.
426 let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
427 let rc_val = C_int(bcx.ccx(), -2);
428 Store(bcx, rc_val, rc);
432 // Type descriptor and type glue stuff
434 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
435 get_tydesc(ccx, t).tydesc
438 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
439 match ccx.tydescs.find(&t) {
446 ccx.stats.n_static_tydescs += 1u;
447 let inf = glue::declare_tydesc(ccx, t);
448 ccx.tydescs.insert(t, inf);
452 pub fn set_optimize_for_size(f: ValueRef) {
453 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
456 pub fn set_no_inline(f: ValueRef) {
457 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
460 pub fn set_no_unwind(f: ValueRef) {
461 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
464 // Tell LLVM to emit the information necessary to unwind the stack for the
466 pub fn set_uwtable(f: ValueRef) {
467 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
470 pub fn set_inline_hint(f: ValueRef) {
471 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
474 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
476 // Set the inline hint if there is one
477 match find_inline_attr(attrs) {
478 InlineHint => set_inline_hint(llfn),
479 InlineAlways => set_always_inline(llfn),
480 InlineNever => set_no_inline(llfn),
481 InlineNone => { /* fallthrough */ }
484 // Add the no-split-stack attribute if requested
485 if contains_name(attrs, "no_split_stack") {
486 set_no_split_stack(llfn);
489 if contains_name(attrs, "cold") {
490 unsafe { llvm::LLVMAddColdAttribute(llfn) }
494 pub fn set_always_inline(f: ValueRef) {
495 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
498 pub fn set_no_split_stack(f: ValueRef) {
499 do "no-split-stack".with_c_str |buf| {
500 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
504 // Double-check that we never ask LLVM to declare the same symbol twice. It
505 // silently mangles such symbols, breaking our linkage model.
506 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
507 if ccx.all_llvm_symbols.contains(&sym) {
508 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
510 ccx.all_llvm_symbols.insert(sym);
514 pub fn get_res_dtor(ccx: @mut CrateContext,
516 parent_id: ast::DefId,
519 let _icx = push_ctxt("trans_res_dtor");
520 let did = if did.crate != ast::LOCAL_CRATE {
521 inline::maybe_instantiate_inline(ccx, did)
525 if !substs.is_empty() {
526 assert_eq!(did.crate, ast::LOCAL_CRATE);
527 let tsubsts = ty::substs {regions: ty::ErasedRegions,
529 tps: /*bad*/ substs.to_owned() };
531 // FIXME: #4252: Generic destructors with type bounds are broken.
533 // Since the vtables aren't passed to `monomorphic_fn` here, generic destructors with type
534 // bounds are broken. Sadly, the `typeck` pass isn't outputting the necessary metadata
535 // because it does so based on method calls present in the AST. Destructor calls are not yet
536 // known about at that stage of compilation, since `trans` handles cleanups.
537 let (val, _) = monomorphize::monomorphic_fn(ccx,
545 } else if did.crate == ast::LOCAL_CRATE {
546 get_item_val(ccx, did.node)
549 let name = csearch::get_symbol(ccx.sess.cstore, did);
550 let class_ty = ty::subst_tps(tcx,
553 ty::lookup_item_type(tcx, parent_id).ty);
554 let llty = type_of_dtor(ccx, class_ty);
555 get_extern_fn(&mut ccx.externs,
558 lib::llvm::CCallConv,
563 // Structural comparison: a rather involved form of glue.
564 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
565 if cx.sess.opts.save_temps {
566 do s.with_c_str |buf| {
568 llvm::LLVMSetValueName(v, buf)
575 // Used only for creating scalar comparison glue.
576 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
578 // NB: This produces an i1, not a Rust bool (i8).
579 pub fn compare_scalar_types(cx: @mut Block,
585 let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
587 match ty::get(t).sty {
588 ty::ty_nil => rslt(cx, f(nil_type)),
589 ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
590 ty::ty_char => rslt(cx, f(unsigned_int)),
591 ty::ty_int(_) => rslt(cx, f(signed_int)),
592 ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
593 ty::ty_float(_) => rslt(cx, f(floating_point)),
596 controlflow::trans_fail(
598 @"attempt to compare values of type type"),
602 // Should never get here, because t is scalar.
603 cx.sess().bug("non-scalar type passed to \
604 compare_scalar_types")
610 // A helper function to do the actual comparison of scalar values.
611 pub fn compare_scalar_values(cx: @mut Block,
617 let _icx = push_ctxt("compare_scalar_values");
618 fn die(cx: @mut Block) -> ! {
619 cx.tcx().sess.bug("compare_scalar_values: must be a\
620 comparison operator");
624 // We don't need to do actual comparisons for nil.
625 // () == () holds but () < () does not.
627 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(true),
628 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(false),
629 // refinements would be nice
635 ast::BiEq => lib::llvm::RealOEQ,
636 ast::BiNe => lib::llvm::RealUNE,
637 ast::BiLt => lib::llvm::RealOLT,
638 ast::BiLe => lib::llvm::RealOLE,
639 ast::BiGt => lib::llvm::RealOGT,
640 ast::BiGe => lib::llvm::RealOGE,
643 return FCmp(cx, cmp, lhs, rhs);
647 ast::BiEq => lib::llvm::IntEQ,
648 ast::BiNe => lib::llvm::IntNE,
649 ast::BiLt => lib::llvm::IntSLT,
650 ast::BiLe => lib::llvm::IntSLE,
651 ast::BiGt => lib::llvm::IntSGT,
652 ast::BiGe => lib::llvm::IntSGE,
655 return ICmp(cx, cmp, lhs, rhs);
659 ast::BiEq => lib::llvm::IntEQ,
660 ast::BiNe => lib::llvm::IntNE,
661 ast::BiLt => lib::llvm::IntULT,
662 ast::BiLe => lib::llvm::IntULE,
663 ast::BiGt => lib::llvm::IntUGT,
664 ast::BiGe => lib::llvm::IntUGE,
667 return ICmp(cx, cmp, lhs, rhs);
672 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
674 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
675 return Load(cx, GEPi(cx, p, idxs));
678 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
679 Store(cx, v, GEPi(cx, p, idxs));
682 // Iterates through the elements of a structural type.
683 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
684 f: val_and_ty_fn) -> @mut Block {
685 let _icx = push_ctxt("iter_structural_ty");
687 fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
688 variant: @ty::VariantInfo,
689 tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
690 let _icx = push_ctxt("iter_variant");
694 for (i, &arg) in variant.args.iter().enumerate() {
696 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
697 ty::subst_tps(tcx, tps, None, arg));
703 match ty::get(t).sty {
704 ty::ty_struct(*) => {
705 let repr = adt::represent_type(cx.ccx(), t);
706 do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
707 for (i, field_ty) in field_tys.iter().enumerate() {
708 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
709 cx = f(cx, llfld_a, field_ty.mt.ty);
713 ty::ty_estr(ty::vstore_fixed(_)) |
714 ty::ty_evec(_, ty::vstore_fixed(_)) => {
715 let (base, len) = tvec::get_base_and_byte_len(cx, av, t);
716 cx = tvec::iter_vec_raw(cx, base, t, len, f);
718 ty::ty_tup(ref args) => {
719 let repr = adt::represent_type(cx.ccx(), t);
720 for (i, arg) in args.iter().enumerate() {
721 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
722 cx = f(cx, llfld_a, *arg);
725 ty::ty_enum(tid, ref substs) => {
728 let repr = adt::represent_type(ccx, t);
729 let variants = ty::enum_variants(ccx.tcx, tid);
730 let n_variants = (*variants).len();
732 // NB: we must hit the discriminant first so that structural
733 // comparison know not to proceed when the discriminants differ.
735 match adt::trans_switch(cx, repr, av) {
736 (_match::single, None) => {
737 cx = iter_variant(cx, repr, av, variants[0],
740 (_match::switch, Some(lldiscrim_a)) => {
741 cx = f(cx, lldiscrim_a, ty::mk_int());
742 let unr_cx = sub_block(cx, "enum-iter-unr");
744 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
746 let next_cx = sub_block(cx, "enum-iter-next");
748 for variant in (*variants).iter() {
750 sub_block(cx, ~"enum-iter-variant-" +
751 variant.disr_val.to_str());
753 iter_variant(variant_cx, repr, av, *variant,
754 substs.tps, |x,y,z| f(x,y,z));
755 match adt::trans_case(cx, repr, variant.disr_val) {
756 _match::single_result(r) => {
757 AddCase(llswitch, r.val, variant_cx.llbb)
759 _ => ccx.sess.unimpl("value from adt::trans_case \
760 in iter_structural_ty")
762 Br(variant_cx, next_cx.llbb);
766 _ => ccx.sess.unimpl("value from adt::trans_switch \
767 in iter_structural_ty")
770 _ => cx.sess().unimpl("type in iter_structural_ty")
775 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::BinOp,
776 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
777 cast_shift_rhs(op, lhs, rhs,
778 |a,b| Trunc(cx, a, b),
779 |a,b| ZExt(cx, a, b))
782 pub fn cast_shift_const_rhs(op: ast::BinOp,
783 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
784 cast_shift_rhs(op, lhs, rhs,
785 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
786 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
789 pub fn cast_shift_rhs(op: ast::BinOp,
792 trunc: |ValueRef, Type| -> ValueRef,
793 zext: |ValueRef, Type| -> ValueRef)
795 // Shifts may have any size int on the rhs
797 if ast_util::is_shift_binop(op) {
798 let rhs_llty = val_ty(rhs);
799 let lhs_llty = val_ty(lhs);
800 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
801 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
804 } else if lhs_sz > rhs_sz {
805 // FIXME (#1877: If shifting by negative
806 // values becomes not undefined then this is wrong.
817 pub fn fail_if_zero(cx: @mut Block, span: Span, divrem: ast::BinOp,
818 rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
819 let text = if divrem == ast::BiDiv {
820 @"attempted to divide by zero"
822 @"attempted remainder with a divisor of zero"
824 let is_zero = match ty::get(rhs_t).sty {
826 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
827 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
830 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
831 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
834 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
835 ty_to_str(cx.ccx().tcx, rhs_t));
838 do with_cond(cx, is_zero) |bcx| {
839 controlflow::trans_fail(bcx, Some(span), text)
843 pub fn null_env_ptr(ccx: &CrateContext) -> ValueRef {
844 C_null(Type::opaque_box(ccx).ptr_to())
847 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
848 let name = csearch::get_symbol(ccx.sess.cstore, did);
849 match ty::get(t).sty {
850 ty::ty_bare_fn(ref fn_ty) => {
851 match fn_ty.abis.for_target(ccx.sess.targ_cfg.os,
852 ccx.sess.targ_cfg.arch) {
853 Some(Rust) | Some(RustIntrinsic) => {
854 get_extern_rust_fn(ccx, fn_ty.sig.inputs, fn_ty.sig.output, name, did)
857 let c = foreign::llvm_calling_convention(ccx, fn_ty.abis);
858 let cconv = c.unwrap_or(lib::llvm::CCallConv);
859 let llty = type_of_fn_from_ty(ccx, t);
860 get_extern_fn(&mut ccx.externs, ccx.llmod, name, cconv, llty)
864 ty::ty_closure(ref f) => {
865 get_extern_rust_fn(ccx, f.sig.inputs, f.sig.output, name, did)
868 let llty = type_of(ccx, t);
869 get_extern_const(&mut ccx.externs, ccx.llmod, name, llty)
874 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef],
875 attributes: &[(uint, lib::llvm::Attribute)])
876 -> (ValueRef, @mut Block) {
877 let _icx = push_ctxt("invoke_");
879 return (C_null(Type::i8()), bcx);
882 match bcx.node_info {
883 None => debug!("invoke at ???"),
885 debug!("invoke at {}",
886 bcx.sess().codemap.span_to_str(node_info.span));
890 if need_invoke(bcx) {
892 debug!("invoking {} at {}", llfn, bcx.llbb);
893 for &llarg in llargs.iter() {
894 debug!("arg: {}", llarg);
897 let normal_bcx = sub_block(bcx, "normal return");
898 let llresult = Invoke(bcx,
902 get_landing_pad(bcx),
904 return (llresult, normal_bcx);
907 debug!("calling {} at {}", llfn, bcx.llbb);
908 for &llarg in llargs.iter() {
909 debug!("arg: {}", llarg);
912 let llresult = Call(bcx, llfn, llargs, attributes);
913 return (llresult, bcx);
917 pub fn need_invoke(bcx: @mut Block) -> bool {
918 if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
922 // Avoid using invoke if we are already inside a landing pad.
927 if have_cached_lpad(bcx) {
931 // Walk the scopes to look for cleanups
933 let mut cur_scope = cur.scope;
935 cur_scope = match cur_scope {
937 for cleanup in inf.cleanups.iter() {
939 clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
940 if cleanup_type == normal_exit_and_unwind {
949 cur = match cur.parent {
959 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
961 do in_lpad_scope_cx(bcx) |inf| {
962 match inf.landing_pad {
963 Some(_) => res = true,
970 pub fn in_lpad_scope_cx(bcx: @mut Block, f: |si: &mut ScopeInfo|) {
972 let mut cur_scope = bcx.scope;
974 cur_scope = match cur_scope {
976 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
983 bcx = block_parent(bcx);
990 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
991 let _icx = push_ctxt("get_landing_pad");
993 let mut cached = None;
994 let mut pad_bcx = bcx; // Guaranteed to be set below
995 do in_lpad_scope_cx(bcx) |inf| {
996 // If there is a valid landing pad still around, use it
997 match inf.landing_pad {
998 Some(target) => cached = Some(target),
1000 pad_bcx = lpad_block(bcx, "unwind");
1001 inf.landing_pad = Some(pad_bcx.llbb);
1005 // Can't return from block above
1006 match cached { Some(b) => return b, None => () }
1007 // The landing pad return type (the type being propagated). Not sure what
1008 // this represents but it's determined by the personality function and
1009 // this is what the EH proposal example uses.
1010 let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
1011 // The exception handling personality function. This is the C++
1012 // personality function __gxx_personality_v0, wrapped in our naming
1014 let personality = bcx.ccx().upcalls.rust_personality;
1015 // The only landing pad clause will be 'cleanup'
1016 let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
1017 // The landing pad block is a cleanup
1018 SetCleanup(pad_bcx, llretval);
1020 // Because we may have unwound across a stack boundary, we must call into
1021 // the runtime to figure out which stack segment we are on and place the
1022 // stack limit back into the TLS.
1023 Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, [], []);
1025 // We store the retval in a function-central alloca, so that calls to
1026 // Resume can find it.
1027 match bcx.fcx.personality {
1028 Some(addr) => Store(pad_bcx, llretval, addr),
1030 let addr = alloca(pad_bcx, val_ty(llretval), "");
1031 bcx.fcx.personality = Some(addr);
1032 Store(pad_bcx, llretval, addr);
1036 // Unwind all parent scopes, and finish with a Resume instr
1037 cleanup_and_leave(pad_bcx, None, None);
1038 return pad_bcx.llbb;
1041 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::NodeId) -> @mut Block {
1042 let mut bcx_sid = bcx;
1043 let mut cur_scope = bcx_sid.scope;
1045 cur_scope = match cur_scope {
1047 match inf.node_info {
1048 Some(NodeInfo { id, _ }) if id == scope_id => {
1051 // FIXME(#6268, #6248) hacky cleanup for nested method calls
1052 Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1059 bcx_sid = match bcx_sid.parent {
1060 None => bcx.tcx().sess.bug(format!("no enclosing scope with id {}", scope_id)),
1061 Some(bcx_par) => bcx_par
1070 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1071 if ty::type_is_bot(t) {
1072 return C_null(Type::i8p());
1074 let llptr = alloc_ty(bcx, t, "");
1075 Store(bcx, v, llptr);
1079 // Since this function does *not* root, it is the caller's responsibility to
1080 // ensure that the referent is pointed to by a root.
1081 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1082 let llptr = alloca(cx, val_ty(v), "");
1083 Store(cx, v, llptr);
1087 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1088 let _icx = push_ctxt("spill_if_immediate");
1089 if type_is_immediate(cx.ccx(), t) { return do_spill(cx, v, t); }
1093 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1094 let _icx = push_ctxt("load_if_immediate");
1095 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
1099 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<Span>, trace_str: @str) {
1100 if !bcx.sess().trace() { return; }
1101 let _icx = push_ctxt("trans_trace");
1102 add_comment(bcx, trace_str);
1103 let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1104 let (V_filename, V_line) = match sp_opt {
1106 let sess = bcx.sess();
1107 let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1108 (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1111 (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1114 let ccx = bcx.ccx();
1115 let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1116 let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1117 let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1118 Call(bcx, ccx.upcalls.trace, args, []);
1121 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1122 match local.pat.node {
1123 ast::PatWild => true, _ => false
1127 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1129 debug!("init_local(bcx={}, local.id={:?})",
1130 bcx.to_str(), local.id);
1131 let _indenter = indenter();
1133 let _icx = push_ctxt("init_local");
1135 if ignore_lhs(bcx, local) {
1136 // Handle let _ = e; just like e;
1139 return expr::trans_into(bcx, init, expr::Ignore);
1141 None => { return bcx; }
1145 _match::store_local(bcx, local.pat, local.init)
1148 pub fn trans_stmt(cx: @mut Block, s: &ast::Stmt) -> @mut Block {
1149 let _icx = push_ctxt("trans_stmt");
1150 debug!("trans_stmt({})", stmt_to_str(s, cx.tcx().sess.intr()));
1152 if cx.sess().asm_comments() {
1153 add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1159 ast::StmtExpr(e, _) | ast::StmtSemi(e, _) => {
1160 bcx = expr::trans_into(cx, e, expr::Ignore);
1162 ast::StmtDecl(d, _) => {
1164 ast::DeclLocal(ref local) => {
1165 bcx = init_local(bcx, *local);
1166 if cx.sess().opts.extra_debuginfo {
1167 debuginfo::create_local_var_metadata(bcx, *local);
1170 ast::DeclItem(i) => trans_item(cx.fcx.ccx, i)
1173 ast::StmtMac(*) => cx.tcx().sess.bug("unexpanded macro")
1179 // You probably don't want to use this one. See the
1180 // next three functions instead.
1181 pub fn new_block(cx: @mut FunctionContext,
1182 parent: Option<@mut Block>,
1183 scope: Option<@mut ScopeInfo>,
1186 opt_node_info: Option<NodeInfo>)
1189 let llbb = do name.with_c_str |buf| {
1190 llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1192 let bcx = @mut Block::new(llbb,
1198 for cx in parent.iter() {
1208 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1209 node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1217 node_info: node_info,
1221 // Use this when you're at the top block of a function or the like.
1222 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1224 return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1225 "function top level", opt_node_info);
1228 pub fn scope_block(bcx: @mut Block,
1229 opt_node_info: Option<NodeInfo>,
1230 n: &str) -> @mut Block {
1231 return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1235 pub fn loop_scope_block(bcx: @mut Block,
1236 loop_break: @mut Block,
1237 loop_label: Option<Name>,
1239 opt_node_info: Option<NodeInfo>) -> @mut Block {
1240 return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1242 loop_break: Some(loop_break),
1243 loop_label: loop_label,
1247 node_info: opt_node_info,
1248 }), bcx.is_lpad, n, opt_node_info);
1251 // Use this when creating a block for the inside of a landing pad.
1252 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1253 new_block(bcx.fcx, Some(bcx), None, true, n, None)
1256 // Use this when you're making a general CFG BB within a scope.
1257 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1258 new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1261 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1262 @mut Block::new(llbb, None, is_lpad, None, fcx)
1266 // trans_block_cleanups: Go through all the cleanups attached to this
1267 // block and execute them.
1269 // When translating a block that introduces new variables during its scope, we
1270 // need to make sure those variables go out of scope when the block ends. We
1271 // do that by running a 'cleanup' function for each variable.
1272 // trans_block_cleanups runs all the cleanup functions for the block.
1273 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1274 trans_block_cleanups_(bcx, cleanups, false)
1277 pub fn trans_block_cleanups_(bcx: @mut Block,
1278 cleanups: &[cleanup],
1279 /* cleanup_cx: block, */
1280 is_lpad: bool) -> @mut Block {
1281 let _icx = push_ctxt("trans_block_cleanups");
1282 // NB: Don't short-circuit even if this block is unreachable because
1283 // GC-based cleanup needs to the see that the roots are live.
1285 bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1286 if bcx.unreachable && !no_lpads { return bcx; }
1288 for cu in cleanups.rev_iter() {
1290 clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1291 // Some types don't need to be cleaned up during
1292 // landing pads because they can be freed en mass later
1293 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1294 bcx = cfn.clean(bcx);
1302 // In the last argument, Some(block) mean jump to this block, and none means
1303 // this is a landing pad and leaving should be accomplished with a resume
1305 pub fn cleanup_and_leave(bcx: @mut Block,
1306 upto: Option<BasicBlockRef>,
1307 leave: Option<BasicBlockRef>) {
1308 let _icx = push_ctxt("cleanup_and_leave");
1311 let is_lpad = leave == None;
1313 debug!("cleanup_and_leave: leaving {}", cur.to_str());
1315 if bcx.sess().trace() {
1318 (format!("cleanup_and_leave({})", cur.to_str())).to_managed());
1321 let mut cur_scope = cur.scope;
1323 cur_scope = match cur_scope {
1324 Some (inf) if !inf.empty_cleanups() => {
1325 let (sub_cx, dest, inf_cleanups) = {
1326 let inf = &mut *inf;
1328 let mut dest = None;
1330 let r = (*inf).cleanup_paths.rev_iter().find(|cp| cp.target == leave);
1331 for cp in r.iter() {
1332 if cp.size == inf.cleanups.len() {
1338 dest = Some(cp.dest);
1341 let sub_cx = sub_block(bcx, "cleanup");
1342 Br(bcx, sub_cx.llbb);
1343 inf.cleanup_paths.push(cleanup_path {
1345 size: inf.cleanups.len(),
1348 (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1350 bcx = trans_block_cleanups_(sub_cx,
1353 for &dest in dest.iter() {
1359 Some(inf) => inf.parent,
1365 Some(bb) => { if cur.llbb == bb { break; } }
1368 cur = match cur.parent {
1370 None => { assert!(upto.is_none()); break; }
1374 Some(target) => Br(bcx, target),
1376 let ll_load = Load(bcx, bcx.fcx.personality.unwrap());
1377 Resume(bcx, ll_load);
1382 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1383 let _icx = push_ctxt("cleanup_block");
1387 debug!("cleanup_block: {}", cur.to_str());
1389 if bcx.sess().trace() {
1392 (format!("cleanup_block({})", cur.to_str())).to_managed());
1395 let mut cur_scope = cur.scope;
1397 cur_scope = match cur_scope {
1399 bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1407 Some(bb) => { if cur.llbb == bb { break; } }
1410 cur = match cur.parent {
1412 None => { assert!(upto.is_none()); break; }
1418 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1419 let _icx = push_ctxt("cleanup_and_Br");
1420 cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1423 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1424 let _icx = push_ctxt("leave_block");
1425 let next_cx = sub_block(block_parent(out_of), "next");
1426 if bcx.unreachable { Unreachable(next_cx); }
1427 cleanup_and_Br(bcx, out_of, next_cx.llbb);
1431 pub fn with_scope(bcx: @mut Block,
1432 opt_node_info: Option<NodeInfo>,
1434 f: |@mut Block| -> @mut Block)
1436 let _icx = push_ctxt("with_scope");
1438 debug!("with_scope(bcx={}, opt_node_info={:?}, name={})",
1439 bcx.to_str(), opt_node_info, name);
1440 let _indenter = indenter();
1442 let scope = simple_block_scope(bcx.scope, opt_node_info);
1443 bcx.scope = Some(scope);
1445 let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1446 bcx.scope = scope.parent;
1450 pub fn with_scope_result(bcx: @mut Block,
1451 opt_node_info: Option<NodeInfo>,
1453 f: |@mut Block| -> Result)
1455 let _icx = push_ctxt("with_scope_result");
1457 let scope = simple_block_scope(bcx.scope, opt_node_info);
1458 bcx.scope = Some(scope);
1459 let Result { bcx: out_bcx, val } = f(bcx);
1460 let out_bcx = trans_block_cleanups_(out_bcx,
1461 (scope.cleanups).clone(),
1463 bcx.scope = scope.parent;
1468 pub fn with_scope_datumblock(bcx: @mut Block,
1469 opt_node_info: Option<NodeInfo>,
1471 f: |@mut Block| -> datum::DatumBlock)
1472 -> datum::DatumBlock {
1473 use middle::trans::datum::DatumBlock;
1475 let _icx = push_ctxt("with_scope_result");
1476 let scope_cx = scope_block(bcx, opt_node_info, name);
1477 Br(bcx, scope_cx.llbb);
1478 let DatumBlock {bcx, datum} = f(scope_cx);
1479 DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1482 pub fn block_locals(b: &ast::Block, it: |@ast::Local|) {
1483 for s in b.stmts.iter() {
1485 ast::StmtDecl(d, _) => {
1487 ast::DeclLocal(ref local) => it(*local),
1488 _ => {} /* fall through */
1491 _ => {} /* fall through */
1496 pub fn with_cond(bcx: @mut Block,
1498 f: |@mut Block| -> @mut Block)
1500 let _icx = push_ctxt("with_cond");
1501 let next_cx = base::sub_block(bcx, "next");
1502 let cond_cx = base::sub_block(bcx, "cond");
1503 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1504 let after_cx = f(cond_cx);
1505 if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1509 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1510 let _icx = push_ctxt("call_memcpy");
1512 let key = match ccx.sess.targ_cfg.arch {
1513 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1514 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1516 let memcpy = ccx.intrinsics.get_copy(&key);
1517 let src_ptr = PointerCast(cx, src, Type::i8p());
1518 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1519 let size = IntCast(cx, n_bytes, ccx.int_type);
1520 let align = C_i32(align as i32);
1521 let volatile = C_i1(false);
1522 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1525 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1526 let _icx = push_ctxt("memcpy_ty");
1527 let ccx = bcx.ccx();
1528 if ty::type_is_structural(t) {
1529 let llty = type_of::type_of(ccx, t);
1530 let llsz = llsize_of(ccx, llty);
1531 let llalign = llalign_of_min(ccx, llty);
1532 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1534 Store(bcx, Load(bcx, src), dst);
1538 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1539 if cx.unreachable { return; }
1540 let _icx = push_ctxt("zero_mem");
1543 let llty = type_of::type_of(ccx, t);
1544 memzero(&B(bcx), llptr, llty);
1547 // Always use this function instead of storing a zero constant to the memory
1548 // in question. If you store a zero constant, LLVM will drown in vreg
1549 // allocation for large data structures, and the generated code will be
1550 // awful. (A telltale sign of this is large quantities of
1551 // `mov [byte ptr foo],0` in the generated code.)
1552 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1553 let _icx = push_ctxt("memzero");
1556 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1557 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1558 X86_64 => "llvm.memset.p0i8.i64"
1561 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1562 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1563 let llzeroval = C_u8(0);
1564 let size = machine::llsize_of(ccx, ty);
1565 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1566 let volatile = C_i1(false);
1567 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1570 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1571 let _icx = push_ctxt("alloc_ty");
1572 let ccx = bcx.ccx();
1573 let ty = type_of::type_of(ccx, t);
1574 assert!(!ty::type_has_params(t));
1575 let val = alloca(bcx, ty, name);
1579 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1580 alloca_maybe_zeroed(cx, ty, name, false)
1583 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1584 let _icx = push_ctxt("alloca");
1587 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1590 let p = Alloca(cx, ty, name);
1592 let b = cx.fcx.ccx.builder();
1593 b.position_before(cx.fcx.alloca_insert_pt.unwrap());
1599 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1600 let _icx = push_ctxt("arrayalloca");
1603 return llvm::LLVMGetUndef(ty.to_ref());
1606 return ArrayAlloca(cx, ty, v);
1609 pub struct BasicBlocks {
1613 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1615 let cx = task_llcx();
1616 do "static_allocas".with_c_str | buf| {
1617 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1622 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1624 let cx = task_llcx();
1625 do "return".with_c_str |buf| {
1626 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1631 // Creates and returns space for, or returns the argument representing, the
1632 // slot where the return value of the function must go.
1633 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1635 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1636 llvm::LLVMGetParam(fcx.llfn, 0)
1638 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1639 let bcx = fcx.entry_bcx.unwrap();
1640 Alloca(bcx, lloutputtype, "__make_return_pointer")
1645 // NB: must keep 4 fns in sync:
1648 // - create_llargs_for_fn_args.
1651 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1657 param_substs: Option<@param_substs>,
1658 opt_node_info: Option<NodeInfo>,
1660 -> @mut FunctionContext {
1661 for p in param_substs.iter() { p.validate(); }
1663 debug!("new_fn_ctxt_w_id(path={}, id={:?}, \
1665 path_str(ccx.sess, path),
1667 param_substs.repr(ccx.tcx));
1669 let substd_output_type = match param_substs {
1670 None => output_type,
1672 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1675 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1676 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1678 let fcx = @mut FunctionContext {
1681 llvm::LLVMGetUndef(Type::i8p().to_ref())
1685 alloca_insert_pt: None,
1689 caller_expects_out_pointer: uses_outptr,
1690 llargs: @mut HashMap::new(),
1691 lllocals: @mut HashMap::new(),
1692 llupvars: @mut HashMap::new(),
1694 param_substs: param_substs,
1698 debug_context: debug_context,
1700 fcx.llenv = unsafe {
1701 llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1705 let entry_bcx = top_scope_block(fcx, opt_node_info);
1706 Load(entry_bcx, C_null(Type::i8p()));
1708 fcx.entry_bcx = Some(entry_bcx);
1709 fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1712 if !ty::type_is_voidish(ccx.tcx, substd_output_type) {
1713 // If the function returns nil/bot, there is no real return
1714 // value, so do not set `llretptr`.
1715 if !skip_retptr || uses_outptr {
1716 // Otherwise, we normally allocate the llretptr, unless we
1717 // have been instructed to skip it for immediate return
1719 fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1725 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1730 -> @mut FunctionContext {
1731 new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1734 // NB: must keep 4 fns in sync:
1737 // - create_llargs_for_fn_args.
1741 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1742 // allocas created for them.
1744 // When we translate a function, we need to map its incoming arguments to the
1745 // spaces that have been created for them (by code in the llallocas field of
1746 // the function's fn_ctxt). create_llargs_for_fn_args populates the llargs
1747 // field of the fn_ctxt with
1748 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1752 let _icx = push_ctxt("create_llargs_for_fn_args");
1755 impl_self(tt, self_mode) => {
1756 cx.llself = Some(ValSelfData {
1759 is_copy: self_mode == ty::ByCopy
1765 // Return an array containing the ValueRefs that we get from
1766 // llvm::LLVMGetParam for each argument.
1767 do vec::from_fn(args.len()) |i| {
1768 unsafe { llvm::LLVMGetParam(cx.llfn, cx.arg_pos(i) as c_uint) }
1772 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1775 raw_llargs: &[ValueRef],
1776 arg_tys: &[ty::t]) -> @mut Block {
1777 debug!("copy_args_to_allocas: raw_llargs={} arg_tys={}",
1778 raw_llargs.llrepr(fcx.ccx),
1779 arg_tys.repr(fcx.ccx.tcx));
1781 let _icx = push_ctxt("copy_args_to_allocas");
1786 let self_val = if slf.is_copy
1787 && datum::appropriate_mode(bcx.ccx(), slf.t).is_by_value() {
1788 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1789 let alloc = alloc_ty(bcx, slf.t, "__self");
1790 Store(bcx, tmp, alloc);
1793 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1796 fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1797 add_clean(bcx, self_val, slf.t);
1799 if fcx.ccx.sess.opts.extra_debuginfo {
1800 debuginfo::create_self_argument_metadata(bcx, slf.t, self_val);
1806 for (arg_n, &arg_ty) in arg_tys.iter().enumerate() {
1807 let raw_llarg = raw_llargs[arg_n];
1809 // For certain mode/type combinations, the raw llarg values are passed
1810 // by value. However, within the fn body itself, we want to always
1811 // have all locals and arguments be by-ref so that we can cancel the
1812 // cleanup and for better interaction with LLVM's debug info. So, if
1813 // the argument would be passed by value, we store it into an alloca.
1814 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1815 // the event it's not truly needed.
1816 // only by value if immediate:
1817 let llarg = if datum::appropriate_mode(bcx.ccx(), arg_ty).is_by_value() {
1818 let alloc = alloc_ty(bcx, arg_ty, "__arg");
1819 Store(bcx, raw_llarg, alloc);
1824 bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1826 if fcx.ccx.sess.opts.extra_debuginfo {
1827 debuginfo::create_argument_metadata(bcx, &args[arg_n]);
1834 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1835 // and builds the return block.
1836 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1837 let _icx = push_ctxt("finish_fn");
1839 let ret_cx = match fcx.llreturn {
1841 if !last_bcx.terminated {
1842 Br(last_bcx, llreturn);
1844 raw_block(fcx, false, llreturn)
1848 build_return_block(fcx, ret_cx);
1852 // Builds the return block for a function.
1853 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1854 // Return the value if this function immediate; otherwise, return void.
1855 if fcx.llretptr.is_none() || fcx.caller_expects_out_pointer {
1856 return RetVoid(ret_cx);
1859 let retptr = Value(fcx.llretptr.unwrap());
1860 let retval = match retptr.get_dominating_store(ret_cx) {
1861 // If there's only a single store to the ret slot, we can directly return
1862 // the value that was stored and omit the store and the alloca
1864 let retval = *s.get_operand(0).unwrap();
1865 s.erase_from_parent();
1867 if retptr.has_no_uses() {
1868 retptr.erase_from_parent();
1873 // Otherwise, load the return value from the ret slot
1874 None => Load(ret_cx, fcx.llretptr.unwrap())
1878 Ret(ret_cx, retval);
1881 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1883 // trans_closure: Builds an LLVM function out of a source function.
1884 // If the function closes over its environment a closure will be
1886 pub fn trans_closure(ccx: @mut CrateContext,
1888 decl: &ast::fn_decl,
1892 param_substs: Option<@param_substs>,
1894 _attributes: &[ast::Attribute],
1896 maybe_load_env: |@mut FunctionContext|) {
1897 ccx.stats.n_closures += 1;
1898 let _icx = push_ctxt("trans_closure");
1899 set_uwtable(llfndecl);
1901 debug!("trans_closure(..., param_substs={})",
1902 param_substs.repr(ccx.tcx));
1904 let fcx = new_fn_ctxt_w_id(ccx,
1914 // Create the first basic block in the function and keep a handle on it to
1915 // pass to finish_fn later.
1916 let bcx_top = fcx.entry_bcx.unwrap();
1917 let mut bcx = bcx_top;
1918 let block_ty = node_id_type(bcx, body.id);
1920 // Set up arguments to the function.
1921 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1922 let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1924 bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1926 maybe_load_env(fcx);
1928 // Up until here, IR instructions for this function have explicitly not been annotated with
1929 // source code location, so we don't step into call setup code. From here on, source location
1930 // emitting should be enabled.
1931 debuginfo::start_emitting_source_locations(fcx);
1933 // This call to trans_block is the place where we bridge between
1934 // translation calls that don't have a return value (trans_crate,
1935 // trans_mod, trans_item, et cetera) and those that do
1936 // (trans_block, trans_expr, et cetera).
1937 if body.expr.is_none() || ty::type_is_voidish(bcx.tcx(), block_ty) {
1938 bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1940 let dest = expr::SaveIn(fcx.llretptr.unwrap());
1941 bcx = controlflow::trans_block(bcx, body, dest);
1944 match fcx.llreturn {
1945 Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1946 None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1949 // Put return block after all other blocks.
1950 // This somewhat improves single-stepping experience in debugger.
1952 for &llreturn in fcx.llreturn.iter() {
1953 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1957 // Insert the mandatory first few basic blocks before lltop.
1958 finish_fn(fcx, bcx);
1961 // trans_fn: creates an LLVM function corresponding to a source language
1963 pub fn trans_fn(ccx: @mut CrateContext,
1965 decl: &ast::fn_decl,
1969 param_substs: Option<@param_substs>,
1971 attrs: &[ast::Attribute]) {
1973 let the_path_str = path_str(ccx.sess, path);
1974 let _s = StatRecorder::new(ccx, the_path_str);
1975 debug!("trans_fn(self_arg={:?}, param_substs={})",
1977 param_substs.repr(ccx.tcx));
1978 let _icx = push_ctxt("trans_fn");
1979 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1993 fn insert_synthetic_type_entries(bcx: @mut Block,
1994 fn_args: &[ast::arg],
1998 * For tuple-like structs and enum-variants, we generate
1999 * synthetic AST nodes for the arguments. These have no types
2000 * in the type table and no entries in the moves table,
2001 * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
2002 * gets upset. This hack of a function bridges the gap by inserting types.
2004 * This feels horrible. I think we should just have a special path
2005 * for these functions and not try to use the generic code, but
2006 * that's not the problem I'm trying to solve right now. - nmatsakis
2009 let tcx = bcx.tcx();
2010 for i in range(0u, fn_args.len()) {
2011 debug!("setting type of argument {} (pat node {}) to {}",
2012 i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
2014 let pat_id = fn_args[i].pat.id;
2015 let arg_ty = arg_tys[i];
2016 tcx.node_types.insert(pat_id as uint, arg_ty);
2020 pub fn trans_enum_variant(ccx: @mut CrateContext,
2021 _enum_id: ast::NodeId,
2022 variant: &ast::variant,
2023 args: &[ast::variant_arg],
2025 param_substs: Option<@param_substs>,
2026 llfndecl: ValueRef) {
2027 let _icx = push_ctxt("trans_enum_variant");
2029 trans_enum_variant_or_tuple_like_struct(
2038 pub fn trans_tuple_struct(ccx: @mut CrateContext,
2039 fields: &[@ast::struct_field],
2040 ctor_id: ast::NodeId,
2041 param_substs: Option<@param_substs>,
2042 llfndecl: ValueRef) {
2043 let _icx = push_ctxt("trans_tuple_struct");
2045 trans_enum_variant_or_tuple_like_struct(
2055 fn id(&self) -> ast::NodeId;
2056 fn ty<'a>(&'a self) -> &'a ast::Ty;
2059 impl IdAndTy for ast::variant_arg {
2060 fn id(&self) -> ast::NodeId { self.id }
2061 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
2064 impl IdAndTy for @ast::struct_field {
2065 fn id(&self) -> ast::NodeId { self.node.id }
2066 fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
2069 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2070 ccx: @mut CrateContext,
2071 ctor_id: ast::NodeId,
2074 param_substs: Option<@param_substs>,
2077 // Translate variant arguments to function arguments.
2078 let fn_args = do args.map |varg| {
2080 ty: (*varg.ty()).clone(),
2081 pat: ast_util::ident_to_pat(
2082 ccx.tcx.sess.next_node_id(),
2083 codemap::dummy_sp(),
2084 special_idents::arg),
2089 let no_substs: &[ty::t] = [];
2090 let ty_param_substs = match param_substs {
2091 Some(ref substs) => {
2092 let v: &[ty::t] = substs.tys;
2096 let v: &[ty::t] = no_substs;
2101 let ctor_ty = ty::subst_tps(ccx.tcx,
2104 ty::node_id_to_type(ccx.tcx, ctor_id));
2106 let result_ty = match ty::get(ctor_ty).sty {
2107 ty::ty_bare_fn(ref bft) => bft.sig.output,
2109 format!("trans_enum_variant_or_tuple_like_struct: \
2110 unexpected ctor return type {}",
2111 ty_to_str(ccx.tcx, ctor_ty)))
2114 let fcx = new_fn_ctxt_w_id(ccx,
2124 let arg_tys = ty::ty_fn_args(ctor_ty);
2126 let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2128 let bcx = fcx.entry_bcx.unwrap();
2130 insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2131 let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2133 let repr = adt::represent_type(ccx, result_ty);
2134 adt::trans_start_init(bcx, repr, fcx.llretptr.unwrap(), disr);
2135 for (i, fn_arg) in fn_args.iter().enumerate() {
2136 let lldestptr = adt::trans_field_ptr(bcx,
2138 fcx.llretptr.unwrap(),
2141 let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2142 let arg_ty = arg_tys[i];
2143 memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2145 finish_fn(fcx, bcx);
2148 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2149 id: ast::NodeId, vi: @~[@ty::VariantInfo],
2151 for variant in enum_definition.variants.iter() {
2152 let disr_val = vi[*i].disr_val;
2155 match variant.node.kind {
2156 ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2157 let llfn = get_item_val(ccx, variant.node.id);
2158 trans_enum_variant(ccx, id, variant, *args,
2159 disr_val, None, llfn);
2161 ast::tuple_variant_kind(_) => {
2164 ast::struct_variant_kind(struct_def) => {
2165 trans_struct_def(ccx, struct_def);
2171 pub struct TransItemVisitor {
2172 ccx: @mut CrateContext,
2175 impl Visitor<()> for TransItemVisitor {
2176 fn visit_item(&mut self, i: @ast::item, _:()) {
2177 trans_item(self.ccx, i);
2181 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2182 let _icx = push_ctxt("trans_item");
2183 let path = match ccx.tcx.items.get_copy(&item.id) {
2184 ast_map::node_item(_, p) => p,
2186 _ => fail!("trans_item"),
2189 ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2190 if purity == ast::extern_fn {
2191 let llfndecl = get_item_val(ccx, item.id);
2192 foreign::trans_rust_fn_with_foreign_abi(
2194 &vec::append((*path).clone(),
2195 [path_name(item.ident)]),
2201 } else if !generics.is_type_parameterized() {
2202 let llfndecl = get_item_val(ccx, item.id);
2204 vec::append((*path).clone(), [path_name(item.ident)]),
2213 // Be sure to travel more than just one layer deep to catch nested
2214 // items in blocks and such.
2215 let mut v = TransItemVisitor{ ccx: ccx };
2216 v.visit_block(body, ());
2219 ast::item_impl(ref generics, _, _, ref ms) => {
2220 meth::trans_impl(ccx,
2227 ast::item_mod(ref m) => {
2230 ast::item_enum(ref enum_definition, ref generics) => {
2231 if !generics.is_type_parameterized() {
2232 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2234 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2237 ast::item_static(_, m, expr) => {
2238 consts::trans_const(ccx, m, item.id);
2239 // Do static_assert checking. It can't really be done much earlier
2240 // because we need to get the value of the bool out of LLVM
2241 if attr::contains_name(item.attrs, "static_assert") {
2242 if m == ast::MutMutable {
2243 ccx.sess.span_fatal(expr.span,
2244 "cannot have static_assert on a mutable \
2247 let v = ccx.const_values.get_copy(&item.id);
2249 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2250 ccx.sess.span_fatal(expr.span, "static assertion failed");
2255 ast::item_foreign_mod(ref foreign_mod) => {
2256 foreign::trans_foreign_mod(ccx, foreign_mod);
2258 ast::item_struct(struct_def, ref generics) => {
2259 if !generics.is_type_parameterized() {
2260 trans_struct_def(ccx, struct_def);
2263 ast::item_trait(*) => {
2264 // Inside of this trait definition, we won't be actually translating any
2265 // functions, but the trait still needs to be walked. Otherwise default
2266 // methods with items will not get translated and will cause ICE's when
2267 // metadata time comes around.
2268 let mut v = TransItemVisitor{ ccx: ccx };
2269 visit::walk_item(&mut v, item, ());
2271 _ => {/* fall through */ }
2275 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2276 // If this is a tuple-like struct, translate the constructor.
2277 match struct_def.ctor_id {
2278 // We only need to translate a constructor if there are fields;
2279 // otherwise this is a unit-like struct.
2280 Some(ctor_id) if struct_def.fields.len() > 0 => {
2281 let llfndecl = get_item_val(ccx, ctor_id);
2282 trans_tuple_struct(ccx, struct_def.fields,
2283 ctor_id, None, llfndecl);
2285 Some(_) | None => {}
2289 // Translate a module. Doing this amounts to translating the items in the
2290 // module; there ends up being no artifact (aside from linkage names) of
2291 // separate modules in the compiled program. That's because modules exist
2292 // only as a convenience for humans working with the code, to organize names
2293 // and control visibility.
2294 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2295 let _icx = push_ctxt("trans_mod");
2296 for item in m.items.iter() {
2297 trans_item(ccx, *item);
2301 fn finish_register_fn(ccx: @mut CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
2303 ccx.item_symbols.insert(node_id, sym);
2305 if !ccx.reachable.contains(&node_id) {
2306 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
2309 // FIXME #4404 android JNI hacks
2310 let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2311 (*ccx.sess.building_library &&
2312 ccx.sess.targ_cfg.os == OsAndroid));
2314 create_entry_wrapper(ccx, sp, llfn);
2318 pub fn register_fn(ccx: @mut CrateContext,
2321 node_id: ast::NodeId,
2324 let f = match ty::get(node_type).sty {
2325 ty::ty_bare_fn(ref f) => {
2326 assert!(f.abis.is_rust() || f.abis.is_intrinsic());
2329 _ => fail!("expected bare rust fn or an intrinsic")
2332 let llfn = decl_rust_fn(ccx, f.sig.inputs, f.sig.output, sym);
2333 finish_register_fn(ccx, sp, sym, node_id, llfn);
2337 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2338 pub fn register_fn_llvmty(ccx: @mut CrateContext,
2341 node_id: ast::NodeId,
2342 cc: lib::llvm::CallConv,
2345 debug!("register_fn_fuller creating fn for item {} with path {}",
2347 ast_map::path_to_str(item_path(ccx, &node_id), token::get_ident_interner()));
2349 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty);
2350 finish_register_fn(ccx, sp, sym, node_id, llfn);
2354 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2355 match *sess.entry_fn {
2356 Some((entry_id, _)) => node_id == entry_id,
2361 // Create a _rust_main(args: ~[str]) function which will be called from the
2362 // runtime rust_start function
2363 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2365 main_llfn: ValueRef) {
2366 let et = ccx.sess.entry_type.unwrap();
2368 session::EntryMain => {
2369 create_entry_fn(ccx, main_llfn, true);
2371 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
2372 session::EntryNone => {} // Do nothing.
2375 fn create_entry_fn(ccx: @mut CrateContext,
2376 rust_main: ValueRef,
2377 use_start_lang_item: bool) {
2378 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2381 // FIXME #4404 android JNI hacks
2382 let main_name = if *ccx.sess.building_library {
2387 let llfn = decl_cdecl_fn(ccx.llmod, main_name, llfty);
2388 let llbb = do "top".with_c_str |buf| {
2390 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2393 let bld = ccx.builder.B;
2395 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2397 let (start_fn, args) = if use_start_lang_item {
2398 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2400 Err(s) => { ccx.tcx.sess.fatal(s); }
2402 let start_fn = if start_def_id.crate == ast::LOCAL_CRATE {
2403 get_item_val(ccx, start_def_id.node)
2405 let start_fn_type = csearch::get_type(ccx.tcx,
2407 trans_external_path(ccx, start_def_id, start_fn_type)
2411 let opaque_rust_main = do "rust_main".with_c_str |buf| {
2412 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2416 C_null(Type::opaque_box(ccx).ptr_to()),
2418 llvm::LLVMGetParam(llfn, 0),
2419 llvm::LLVMGetParam(llfn, 1)
2424 debug!("using user-defined start fn");
2426 C_null(Type::opaque_box(ccx).ptr_to()),
2427 llvm::LLVMGetParam(llfn, 0 as c_uint),
2428 llvm::LLVMGetParam(llfn, 1 as c_uint)
2434 let result = do args.as_imm_buf |buf, len| {
2435 llvm::LLVMBuildCall(bld, start_fn, buf, len as c_uint, noname())
2438 llvm::LLVMBuildRet(bld, result);
2443 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2444 llenvptr: ValueRef) {
2445 let ccx = bcx.ccx();
2446 let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2447 Store(bcx, llfn, code_cell);
2448 let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2449 let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2450 Store(bcx, llenvblobptr, env_cell);
2453 pub fn item_path(ccx: &CrateContext, id: &ast::NodeId) -> path {
2454 ty::item_path(ccx.tcx, ast_util::local_def(*id))
2457 fn exported_name(ccx: &mut CrateContext, path: path, ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
2458 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2459 // Use provided name
2460 Some(name) => name.to_owned(),
2463 _ if attr::contains_name(attrs, "no_mangle")
2464 => path_elt_to_str(*path.last(), token::get_ident_interner()),
2466 // Usual name mangling
2467 _ => mangle_exported_name(ccx, path, ty)
2471 pub fn get_item_val(ccx: @mut CrateContext, id: ast::NodeId) -> ValueRef {
2472 debug!("get_item_val(id=`{:?}`)", id);
2474 let val = ccx.item_vals.find_copy(&id);
2478 let mut foreign = false;
2479 let item = ccx.tcx.items.get_copy(&id);
2480 let val = match item {
2481 ast_map::node_item(i, pth) => {
2483 let elt = path_pretty_name(i.ident, id as u64);
2484 let my_path = vec::append_one((*pth).clone(), elt);
2485 let ty = ty::node_id_to_type(ccx.tcx, i.id);
2486 let sym = exported_name(ccx, my_path, ty, i.attrs);
2488 let v = match i.node {
2489 ast::item_static(_, _, expr) => {
2490 // If this static came from an external crate, then
2491 // we need to get the symbol from csearch instead of
2492 // using the current crate's name/version
2493 // information in the hash of the symbol
2494 debug!("making {}", sym);
2495 let sym = match ccx.external_srcs.find(&i.id) {
2497 debug!("but found in other crate...");
2498 csearch::get_symbol(ccx.sess.cstore, did)
2503 // We need the translated value here, because for enums the
2504 // LLVM type is not fully determined by the Rust type.
2505 let (v, inlineable) = consts::const_expr(ccx, expr);
2506 ccx.const_values.insert(id, v);
2507 let mut inlineable = inlineable;
2510 let llty = llvm::LLVMTypeOf(v);
2511 let g = do sym.with_c_str |buf| {
2512 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2515 if !ccx.reachable.contains(&id) {
2516 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
2519 // Apply the `unnamed_addr` attribute if
2521 if attr::contains_name(i.attrs,
2522 "address_insignificant"){
2523 lib::llvm::SetUnnamedAddr(g, true);
2524 lib::llvm::SetLinkage(g,
2525 lib::llvm::InternalLinkage);
2527 // This is a curious case where we must make
2528 // all of these statics inlineable. If a
2529 // global is tagged as
2530 // address_insignificant, then LLVM won't
2531 // coalesce globals unless they have an
2532 // internal linkage type. This means that
2533 // external crates cannot use this global.
2534 // This is a problem for things like inner
2535 // statics in generic functions, because the
2536 // function will be inlined into another
2537 // crate and then attempt to link to the
2538 // static in the original crate, only to
2539 // find that it's not there. On the other
2540 // side of inlininig, the crates knows to
2541 // not declare this static as
2542 // available_externally (because it isn't)
2547 debug!("{} not inlined", sym);
2548 ccx.non_inlineable_statics.insert(id);
2550 ccx.item_symbols.insert(i.id, sym);
2555 ast::item_fn(_, purity, _, _, _) => {
2556 let llfn = if purity != ast::extern_fn {
2557 register_fn(ccx, i.span, sym, i.id, ty)
2559 foreign::register_rust_fn_with_foreign_abi(ccx,
2564 set_llvm_fn_attrs(i.attrs, llfn);
2568 _ => fail!("get_item_val: weird result in table")
2571 match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2572 Some(sect) => unsafe {
2573 do sect.with_c_str |buf| {
2574 llvm::LLVMSetSection(v, buf);
2583 ast_map::node_trait_method(trait_method, _, pth) => {
2584 debug!("get_item_val(): processing a node_trait_method");
2585 match *trait_method {
2586 ast::required(_) => {
2587 ccx.sess.bug("unexpected variant: required trait method in \
2590 ast::provided(m) => {
2591 register_method(ccx, id, pth, m)
2596 ast_map::node_method(m, _, pth) => {
2597 register_method(ccx, id, pth, m)
2600 ast_map::node_foreign_item(ni, abis, _, pth) => {
2601 let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2605 ast::foreign_item_fn(*) => {
2606 let path = vec::append((*pth).clone(), [path_name(ni.ident)]);
2607 foreign::register_foreign_item_fn(ccx, abis, &path, ni)
2609 ast::foreign_item_static(*) => {
2610 // Treat the crate map static specially in order to
2611 // a weak-linkage-like functionality where it's
2612 // dynamically resolved at runtime. If we're
2613 // building a library, then we declare the static
2614 // with weak linkage, but if we're building a
2615 // library then we've already declared the crate map
2616 // so use that instead.
2617 if attr::contains_name(ni.attrs, "crate_map") {
2618 if *ccx.sess.building_library {
2619 let s = "_rust_crate_map_toplevel";
2620 let g = unsafe { do s.with_c_str |buf| {
2621 let ty = type_of(ccx, ty);
2622 llvm::LLVMAddGlobal(ccx.llmod,
2625 lib::llvm::SetLinkage(g,
2626 lib::llvm::ExternalWeakLinkage);
2632 let ident = foreign::link_name(ccx, ni);
2634 do ident.with_c_str |buf| {
2635 let ty = type_of(ccx, ty);
2636 llvm::LLVMAddGlobal(ccx.llmod,
2645 ast_map::node_variant(ref v, enm, pth) => {
2648 ast::tuple_variant_kind(ref args) => {
2649 assert!(args.len() != 0u);
2650 let pth = vec::append((*pth).clone(),
2651 [path_name(enm.ident),
2652 path_name((*v).node.name)]);
2653 let ty = ty::node_id_to_type(ccx.tcx, id);
2654 let sym = exported_name(ccx, pth, ty, enm.attrs);
2656 llfn = match enm.node {
2657 ast::item_enum(_, _) => {
2658 register_fn(ccx, (*v).span, sym, id, ty)
2660 _ => fail!("node_variant, shouldn't happen")
2663 ast::struct_variant_kind(_) => {
2664 fail!("struct variant kind unexpected in get_item_val")
2667 set_inline_hint(llfn);
2671 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2672 // Only register the constructor if this is a tuple-like struct.
2673 match struct_def.ctor_id {
2675 ccx.tcx.sess.bug("attempt to register a constructor of \
2676 a non-tuple-like struct")
2679 let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2680 let sym = exported_name(ccx, (*struct_path).clone(), ty,
2682 let llfn = register_fn(ccx, struct_item.span,
2684 set_inline_hint(llfn);
2691 ccx.sess.bug(format!("get_item_val(): unexpected variant: {:?}",
2696 // foreign items (extern fns and extern statics) don't have internal
2697 // linkage b/c that doesn't quite make sense. Otherwise items can
2698 // have internal linkage if they're not reachable.
2699 if !foreign && !ccx.reachable.contains(&id) {
2700 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2703 ccx.item_vals.insert(id, val);
2709 pub fn register_method(ccx: @mut CrateContext,
2711 path: @ast_map::path,
2712 m: @ast::method) -> ValueRef {
2713 let mty = ty::node_id_to_type(ccx.tcx, id);
2715 let mut path = (*path).clone();
2716 path.push(path_pretty_name(m.ident, token::gensym("meth") as u64));
2718 let sym = exported_name(ccx, path, mty, m.attrs);
2720 let llfn = register_fn(ccx, m.span, sym, id, mty);
2721 set_llvm_fn_attrs(m.attrs, llfn);
2725 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2727 return PtrToInt(cx, v, ccx.int_type);
2730 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2732 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2737 ($intrinsics:ident, $name:expr, $args:expr, $ret:expr) => ({
2739 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2740 $intrinsics.insert(name, f);
2744 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2745 let i8p = Type::i8p();
2746 let mut intrinsics = HashMap::new();
2748 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i32",
2749 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2750 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i64",
2751 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2752 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i32",
2753 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2754 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i64",
2755 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2756 ifn!(intrinsics, "llvm.memset.p0i8.i32",
2757 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2758 ifn!(intrinsics, "llvm.memset.p0i8.i64",
2759 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2761 ifn!(intrinsics, "llvm.trap", [], Type::void());
2762 ifn!(intrinsics, "llvm.debugtrap", [], Type::void());
2763 ifn!(intrinsics, "llvm.frameaddress", [Type::i32()], i8p);
2765 ifn!(intrinsics, "llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2766 ifn!(intrinsics, "llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2767 ifn!(intrinsics, "llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2768 ifn!(intrinsics, "llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2770 ifn!(intrinsics, "llvm.sqrt.f32", [Type::f32()], Type::f32());
2771 ifn!(intrinsics, "llvm.sqrt.f64", [Type::f64()], Type::f64());
2772 ifn!(intrinsics, "llvm.sin.f32", [Type::f32()], Type::f32());
2773 ifn!(intrinsics, "llvm.sin.f64", [Type::f64()], Type::f64());
2774 ifn!(intrinsics, "llvm.cos.f32", [Type::f32()], Type::f32());
2775 ifn!(intrinsics, "llvm.cos.f64", [Type::f64()], Type::f64());
2776 ifn!(intrinsics, "llvm.exp.f32", [Type::f32()], Type::f32());
2777 ifn!(intrinsics, "llvm.exp.f64", [Type::f64()], Type::f64());
2778 ifn!(intrinsics, "llvm.exp2.f32", [Type::f32()], Type::f32());
2779 ifn!(intrinsics, "llvm.exp2.f64", [Type::f64()], Type::f64());
2780 ifn!(intrinsics, "llvm.log.f32", [Type::f32()], Type::f32());
2781 ifn!(intrinsics, "llvm.log.f64", [Type::f64()], Type::f64());
2782 ifn!(intrinsics, "llvm.log10.f32",[Type::f32()], Type::f32());
2783 ifn!(intrinsics, "llvm.log10.f64",[Type::f64()], Type::f64());
2784 ifn!(intrinsics, "llvm.log2.f32", [Type::f32()], Type::f32());
2785 ifn!(intrinsics, "llvm.log2.f64", [Type::f64()], Type::f64());
2787 ifn!(intrinsics, "llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2788 ifn!(intrinsics, "llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2790 ifn!(intrinsics, "llvm.fabs.f32", [Type::f32()], Type::f32());
2791 ifn!(intrinsics, "llvm.fabs.f64", [Type::f64()], Type::f64());
2792 ifn!(intrinsics, "llvm.copysign.f32", [Type::f32(), Type::f32()], Type::f32());
2793 ifn!(intrinsics, "llvm.copysign.f64", [Type::f64(), Type::f64()], Type::f64());
2795 ifn!(intrinsics, "llvm.floor.f32",[Type::f32()], Type::f32());
2796 ifn!(intrinsics, "llvm.floor.f64",[Type::f64()], Type::f64());
2797 ifn!(intrinsics, "llvm.ceil.f32", [Type::f32()], Type::f32());
2798 ifn!(intrinsics, "llvm.ceil.f64", [Type::f64()], Type::f64());
2799 ifn!(intrinsics, "llvm.trunc.f32",[Type::f32()], Type::f32());
2800 ifn!(intrinsics, "llvm.trunc.f64",[Type::f64()], Type::f64());
2802 ifn!(intrinsics, "llvm.rint.f32", [Type::f32()], Type::f32());
2803 ifn!(intrinsics, "llvm.rint.f64", [Type::f64()], Type::f64());
2804 ifn!(intrinsics, "llvm.nearbyint.f32", [Type::f32()], Type::f32());
2805 ifn!(intrinsics, "llvm.nearbyint.f64", [Type::f64()], Type::f64());
2806 ifn!(intrinsics, "llvm.round.f32", [Type::f32()], Type::f32());
2807 ifn!(intrinsics, "llvm.round.f64", [Type::f64()], Type::f64());
2809 ifn!(intrinsics, "llvm.ctpop.i8", [Type::i8()], Type::i8());
2810 ifn!(intrinsics, "llvm.ctpop.i16",[Type::i16()], Type::i16());
2811 ifn!(intrinsics, "llvm.ctpop.i32",[Type::i32()], Type::i32());
2812 ifn!(intrinsics, "llvm.ctpop.i64",[Type::i64()], Type::i64());
2814 ifn!(intrinsics, "llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2815 ifn!(intrinsics, "llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2816 ifn!(intrinsics, "llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2817 ifn!(intrinsics, "llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2819 ifn!(intrinsics, "llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2820 ifn!(intrinsics, "llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2821 ifn!(intrinsics, "llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2822 ifn!(intrinsics, "llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2824 ifn!(intrinsics, "llvm.bswap.i16",[Type::i16()], Type::i16());
2825 ifn!(intrinsics, "llvm.bswap.i32",[Type::i32()], Type::i32());
2826 ifn!(intrinsics, "llvm.bswap.i64",[Type::i64()], Type::i64());
2828 ifn!(intrinsics, "llvm.sadd.with.overflow.i8",
2829 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2830 ifn!(intrinsics, "llvm.sadd.with.overflow.i16",
2831 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2832 ifn!(intrinsics, "llvm.sadd.with.overflow.i32",
2833 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2834 ifn!(intrinsics, "llvm.sadd.with.overflow.i64",
2835 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2837 ifn!(intrinsics, "llvm.uadd.with.overflow.i8",
2838 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2839 ifn!(intrinsics, "llvm.uadd.with.overflow.i16",
2840 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2841 ifn!(intrinsics, "llvm.uadd.with.overflow.i32",
2842 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2843 ifn!(intrinsics, "llvm.uadd.with.overflow.i64",
2844 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2846 ifn!(intrinsics, "llvm.ssub.with.overflow.i8",
2847 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2848 ifn!(intrinsics, "llvm.ssub.with.overflow.i16",
2849 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2850 ifn!(intrinsics, "llvm.ssub.with.overflow.i32",
2851 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2852 ifn!(intrinsics, "llvm.ssub.with.overflow.i64",
2853 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2855 ifn!(intrinsics, "llvm.usub.with.overflow.i8",
2856 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2857 ifn!(intrinsics, "llvm.usub.with.overflow.i16",
2858 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2859 ifn!(intrinsics, "llvm.usub.with.overflow.i32",
2860 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2861 ifn!(intrinsics, "llvm.usub.with.overflow.i64",
2862 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2864 ifn!(intrinsics, "llvm.smul.with.overflow.i8",
2865 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2866 ifn!(intrinsics, "llvm.smul.with.overflow.i16",
2867 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2868 ifn!(intrinsics, "llvm.smul.with.overflow.i32",
2869 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2870 ifn!(intrinsics, "llvm.smul.with.overflow.i64",
2871 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2873 ifn!(intrinsics, "llvm.umul.with.overflow.i8",
2874 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2875 ifn!(intrinsics, "llvm.umul.with.overflow.i16",
2876 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2877 ifn!(intrinsics, "llvm.umul.with.overflow.i32",
2878 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2879 ifn!(intrinsics, "llvm.umul.with.overflow.i64",
2880 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2882 ifn!(intrinsics, "llvm.expect.i1", [Type::i1(), Type::i1()], Type::i1());
2887 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2888 ifn!(intrinsics, "llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2890 "llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2893 pub fn trap(bcx: @mut Block) {
2894 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2895 Some(&x) => { Call(bcx, x, [], []); },
2896 _ => bcx.sess().bug("unbound llvm.trap in trap")
2900 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2901 if !ccx.sess.opts.gc || !ccx.uses_gc {
2905 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2906 let gc_metadata = do gc_metadata_name.with_c_str |buf| {
2908 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2912 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2913 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2914 ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2918 pub fn create_module_map(ccx: &mut CrateContext) -> (ValueRef, uint) {
2919 let str_slice_type = Type::struct_([Type::i8p(), ccx.int_type], false);
2920 let elttype = Type::struct_([str_slice_type, ccx.int_type], false);
2921 let maptype = Type::array(&elttype, ccx.module_data.len() as u64);
2922 let map = do "_rust_mod_map".with_c_str |buf| {
2924 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2927 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2928 let mut elts: ~[ValueRef] = ~[];
2930 // This is not ideal, but the borrow checker doesn't
2931 // like the multiple borrows. At least, it doesn't
2932 // like them on the current snapshot. (2013-06-14)
2934 for (k, _) in ccx.module_data.iter() {
2935 keys.push(k.to_managed());
2938 for key in keys.iter() {
2939 let val = *ccx.module_data.find_equiv(key).unwrap();
2940 let v_ptr = p2i(ccx, val);
2941 let elt = C_struct([
2942 C_estr_slice(ccx, *key),
2948 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2950 return (map, keys.len())
2954 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2955 llmod: ModuleRef) -> ValueRef {
2956 let targ_cfg = sess.targ_cfg;
2957 let int_type = Type::int(targ_cfg.arch);
2958 let mut n_subcrates = 1;
2959 let cstore = sess.cstore;
2960 while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2961 let mapname = if *sess.building_library && !sess.gen_crate_map() {
2962 format!("{}_{}_{}", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2967 let sym_name = ~"_rust_crate_map_" + mapname;
2968 let slicetype = Type::struct_([int_type, int_type], false);
2969 let maptype = Type::struct_([
2970 Type::i32(), // version
2971 slicetype, // child modules
2972 slicetype, // sub crate-maps
2973 int_type.ptr_to(), // event loop factory
2975 let map = do sym_name.with_c_str |buf| {
2977 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2980 // On windows we'd like to export the toplevel cratemap
2981 // such that we can find it from libstd.
2982 if targ_cfg.os == OsWin32 && "toplevel" == mapname {
2983 lib::llvm::SetLinkage(map, lib::llvm::DLLExportLinkage);
2985 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2991 pub fn fill_crate_map(ccx: &mut CrateContext, map: ValueRef) {
2992 let mut subcrates: ~[ValueRef] = ~[];
2994 let cstore = ccx.sess.cstore;
2995 while cstore::have_crate_data(cstore, i) {
2996 let cdata = cstore::get_crate_data(cstore, i);
2997 let nm = format!("_rust_crate_map_{}_{}_{}",
2999 cstore::get_crate_vers(cstore, i),
3000 cstore::get_crate_hash(cstore, i));
3001 let cr = do nm.with_c_str |buf| {
3003 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
3006 subcrates.push(p2i(ccx, cr));
3009 let event_loop_factory = if !*ccx.sess.building_library {
3010 match ccx.tcx.lang_items.event_loop_factory() {
3011 Some(did) => unsafe {
3012 let name = csearch::get_symbol(ccx.sess.cstore, did);
3013 let global = do name.with_c_str |buf| {
3014 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
3018 None => C_null(ccx.int_type.ptr_to())
3021 C_null(ccx.int_type.ptr_to())
3024 let maptype = Type::array(&ccx.int_type, subcrates.len() as u64);
3025 let vec_elements = do "_crate_map_child_vectors".with_c_str |buf| {
3026 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
3028 lib::llvm::SetLinkage(vec_elements, lib::llvm::InternalLinkage);
3030 llvm::LLVMSetInitializer(vec_elements, C_array(ccx.int_type, subcrates));
3031 let (mod_map, mod_count) = create_module_map(ccx);
3033 llvm::LLVMSetInitializer(map, C_struct(
3037 C_uint(ccx, mod_count)
3040 p2i(ccx, vec_elements),
3041 C_uint(ccx, subcrates.len())
3048 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
3049 -> encoder::EncodeParams<'r> {
3051 let diag = cx.sess.diagnostic();
3052 let item_symbols = &cx.item_symbols;
3053 let discrim_symbols = &cx.discrim_symbols;
3054 let link_meta = &cx.link_meta;
3055 encoder::EncodeParams {
3058 reexports2: cx.exp_map2,
3059 item_symbols: item_symbols,
3060 discrim_symbols: discrim_symbols,
3061 non_inlineable_statics: &cx.non_inlineable_statics,
3062 link_meta: link_meta,
3063 cstore: cx.sess.cstore,
3064 encode_inlined_item: ie,
3065 reachable: cx.reachable,
3069 pub fn write_metadata(cx: &CrateContext, crate: &ast::Crate) {
3070 if !*cx.sess.building_library { return; }
3072 let encode_inlined_item: encoder::encode_inlined_item =
3073 |ecx, ebml_w, path, ii|
3074 astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
3076 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
3077 let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
3078 let llconst = C_struct([llmeta], false);
3079 let mut llglobal = do "rust_metadata".with_c_str |buf| {
3081 llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
3085 llvm::LLVMSetInitializer(llglobal, llconst);
3086 do cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str |buf| {
3087 llvm::LLVMSetSection(llglobal, buf)
3089 lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
3091 let t_ptr_i8 = Type::i8p();
3092 llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
3093 let llvm_used = do "llvm.used".with_c_str |buf| {
3094 llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
3096 lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
3097 llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
3101 // Writes the current ABI version into the crate.
3102 pub fn write_abi_version(ccx: &mut CrateContext) {
3104 let llval = C_uint(ccx, abi::abi_version);
3105 let llglobal = do "rust_abi_version".with_c_str |buf| {
3106 llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
3108 llvm::LLVMSetInitializer(llglobal, llval);
3109 llvm::LLVMSetGlobalConstant(llglobal, True);
3113 pub fn trans_crate(sess: session::Session,
3115 analysis: &CrateAnalysis,
3116 output: &Path) -> CrateTranslation {
3117 // Before we touch LLVM, make sure that multithreading is enabled.
3118 if unsafe { !llvm::LLVMRustStartMultithreading() } {
3119 sess.bug("couldn't enable multi-threaded LLVM");
3122 let mut symbol_hasher = hash::default_state();
3123 let link_meta = link::build_link_meta(sess, &crate, output,
3124 &mut symbol_hasher);
3126 // Append ".rc" to crate name as LLVM module identifier.
3128 // LLVM code generator emits a ".file filename" directive
3129 // for ELF backends. Value of the "filename" is set as the
3130 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
3131 // crashes if the module identifer is same as other symbols
3132 // such as a function name in the module.
3133 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
3134 let llmod_id = link_meta.name.to_owned() + ".rc";
3136 let ccx = @mut CrateContext::new(sess,
3143 analysis.reachable);
3145 let _icx = push_ctxt("text");
3146 trans_mod(ccx, &crate.module);
3149 decl_gc_metadata(ccx, llmod_id);
3150 fill_crate_map(ccx, ccx.crate_map);
3152 // NOTE win32: wart with exporting crate_map symbol
3153 // We set the crate map (_rust_crate_map_toplevel) to use dll_export
3154 // linkage but that ends up causing the linker to look for a
3155 // __rust_crate_map_toplevel symbol (extra underscore) which it will
3156 // subsequently fail to find. So to mitigate that we just introduce
3157 // an alias from the symbol it expects to the one that actually exists.
3158 if ccx.sess.targ_cfg.os == OsWin32 &&
3159 !*ccx.sess.building_library {
3161 let maptype = val_ty(ccx.crate_map).to_ref();
3163 do "__rust_crate_map_toplevel".with_c_str |buf| {
3165 llvm::LLVMAddAlias(ccx.llmod, maptype,
3166 ccx.crate_map, buf);
3171 glue::emit_tydescs(ccx);
3172 write_abi_version(ccx);
3173 if ccx.sess.opts.debuginfo {
3174 debuginfo::finalize(ccx);
3177 // Translate the metadata.
3178 write_metadata(ccx, &crate);
3179 if ccx.sess.trans_stats() {
3180 println("--- trans stats ---");
3181 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs);
3182 println!("n_glues_created: {}", ccx.stats.n_glues_created);
3183 println!("n_null_glues: {}", ccx.stats.n_null_glues);
3184 println!("n_real_glues: {}", ccx.stats.n_real_glues);
3186 println!("n_fns: {}", ccx.stats.n_fns);
3187 println!("n_monos: {}", ccx.stats.n_monos);
3188 println!("n_inlines: {}", ccx.stats.n_inlines);
3189 println!("n_closures: {}", ccx.stats.n_closures);
3190 println("fn stats:");
3191 do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3194 for tuple in ccx.stats.fn_stats.iter() {
3196 (ref name, ms, insns) => {
3197 println!("{} insns, {} ms, {}", insns, ms, *name);
3202 if ccx.sess.count_llvm_insns() {
3203 for (k, v) in ccx.stats.llvm_insns.iter() {
3204 println!("{:7u} {}", *v, *k);
3208 let llcx = ccx.llcx;
3209 let link_meta = ccx.link_meta;
3210 let llmod = ccx.llmod;
3212 return CrateTranslation {