1 // Copyright 2012-2014 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 one TypeRef corresponds to many `ty::t`s; for instance, tup(int, int,
24 // int) and rec(x=int, y=int, z=int) will have the same TypeRef.
26 #[allow(non_camel_case_types)];
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
31 use driver::session::{Session, NoDebugInfo, FullDebugInfo};
32 use driver::driver::OutputFilenames;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
34 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
35 use lib::llvm::{llvm, True, Vector};
37 use metadata::common::LinkMeta;
38 use metadata::{csearch, encoder};
39 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
42 use middle::trans::_match;
43 use middle::trans::adt;
44 use middle::trans::build::*;
45 use middle::trans::builder::{Builder, noname};
46 use middle::trans::callee;
47 use middle::trans::cleanup;
48 use middle::trans::cleanup::CleanupMethods;
49 use middle::trans::common::*;
50 use middle::trans::consts;
51 use middle::trans::controlflow;
52 use middle::trans::datum;
53 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
54 use middle::trans::debuginfo;
55 use middle::trans::expr;
56 use middle::trans::foreign;
57 use middle::trans::glue;
58 use middle::trans::inline;
59 use middle::trans::machine;
60 use middle::trans::machine::{llalign_of_min, llsize_of};
61 use middle::trans::meth;
62 use middle::trans::monomorphize;
63 use middle::trans::tvec;
64 use middle::trans::type_::Type;
65 use middle::trans::type_of;
66 use middle::trans::type_of::*;
67 use middle::trans::value::Value;
70 use util::common::indenter;
71 use util::ppaux::{Repr, ty_to_str};
72 use util::sha2::Sha256;
73 use util::nodemap::NodeMap;
75 use arena::TypedArena;
76 use std::c_str::ToCStr;
77 use std::cell::{Cell, RefCell};
78 use collections::HashMap;
79 use std::libc::c_uint;
81 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic, OsWin32};
82 use syntax::ast_map::PathName;
83 use syntax::ast_util::{local_def, is_local};
84 use syntax::attr::AttrMetaMethods;
86 use syntax::codemap::Span;
87 use syntax::parse::token::InternedString;
88 use syntax::parse::token;
89 use syntax::visit::Visitor;
91 use syntax::{ast, ast_util, ast_map};
95 pub use middle::trans::context::task_llcx;
97 local_data_key!(task_local_insn_key: ~[&'static str])
99 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
100 local_data::get(task_local_insn_key, |c| {
102 Some(ctx) => blk(*ctx),
108 pub fn init_insn_ctxt() {
109 local_data::set(task_local_insn_key, ~[]);
112 pub struct _InsnCtxt { _x: () }
115 impl Drop for _InsnCtxt {
117 local_data::modify(task_local_insn_key, |c| {
126 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
127 debug!("new InsnCtxt: {}", s);
128 local_data::modify(task_local_insn_key, |c| {
137 pub struct StatRecorder {
145 pub fn new(ccx: @CrateContext, name: ~str) -> StatRecorder {
146 let start = if ccx.sess.trans_stats() {
147 time::precise_time_ns()
151 let istart = ccx.stats.n_llvm_insns.get();
162 impl Drop for StatRecorder {
164 if self.ccx.sess.trans_stats() {
165 let end = time::precise_time_ns();
166 let elapsed = ((end - self.start) / 1_000_000) as uint;
167 let iend = self.ccx.stats.n_llvm_insns.get();
169 let mut fn_stats = self.ccx.stats.fn_stats.borrow_mut();
170 fn_stats.get().push((self.name.take_unwrap(),
172 iend - self.istart));
174 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
175 // Reset LLVM insn count to avoid compound costs.
176 self.ccx.stats.n_llvm_insns.set(self.istart);
181 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
182 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
183 ty: Type, output: ty::t) -> ValueRef {
184 let llfn: ValueRef = name.with_c_str(|buf| {
186 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
190 match ty::get(output).sty {
191 // functions returning bottom may unwind, but can never return normally
194 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
197 // `~` pointer return values never alias because ownership is transferred
198 // FIXME #6750 ~Trait cannot be directly marked as
199 // noalias because the actual object pointer is nested.
200 ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
201 ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) => {
203 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
209 lib::llvm::SetFunctionCallConv(llfn, cc);
210 // Function addresses in Rust are never significant, allowing functions to be merged.
211 lib::llvm::SetUnnamedAddr(llfn, true);
216 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
217 pub fn decl_cdecl_fn(llmod: ModuleRef,
220 output: ty::t) -> ValueRef {
221 decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
224 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
225 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
226 name: &str, cc: lib::llvm::CallConv,
227 ty: Type, output: ty::t) -> ValueRef {
228 match externs.find_equiv(&name) {
229 Some(n) => return *n,
232 let f = decl_fn(llmod, name, cc, ty, output);
233 externs.insert(name.to_owned(), f);
237 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
238 name: &str, did: ast::DefId) -> ValueRef {
240 let externs = ccx.externs.borrow();
241 match externs.get().find_equiv(&name) {
242 Some(n) => return *n,
247 let f = decl_rust_fn(ccx, false, inputs, output, name);
248 csearch::get_item_attrs(ccx.tcx.cstore, did, |meta_items| {
249 set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).to_owned_vec(), f)
252 let mut externs = ccx.externs.borrow_mut();
253 externs.get().insert(name.to_owned(), f);
257 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
258 inputs: &[ty::t], output: ty::t,
259 name: &str) -> ValueRef {
260 let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
261 let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
263 let uses_outptr = type_of::return_uses_outptr(ccx, output);
264 let offset = if uses_outptr { 1 } else { 0 };
265 let offset = if has_env { offset + 1 } else { offset };
267 for (i, &arg_ty) in inputs.iter().enumerate() {
268 let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
269 match ty::get(arg_ty).sty {
270 // `~` pointer parameters never alias because ownership is transferred
271 // FIXME #6750 ~Trait cannot be directly marked as
272 // noalias because the actual object pointer is nested.
273 ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
274 ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) |
275 ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, ..}) => {
277 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
281 // For non-immediate arguments the callee gets its own copy of
282 // the value on the stack, so there are no aliases
283 if !type_is_immediate(ccx, arg_ty) {
285 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
286 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
293 // The out pointer will never alias with any other pointers, as the object only exists at a
294 // language level after the call. It can also be tagged with SRet to indicate that it is
295 // guaranteed to point to a usable block of memory for the type.
298 let outptr = llvm::LLVMGetParam(llfn, 0);
299 llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
300 llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
307 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
308 inputs: &[ty::t], output: ty::t,
309 name: &str) -> ValueRef {
310 let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
311 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
315 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
316 name: &str, ty: Type) -> ValueRef {
317 match externs.find_equiv(&name) {
318 Some(n) => return *n,
322 let c = name.with_c_str(|buf| {
323 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
325 externs.insert(name.to_owned(), c);
330 // Returns a pointer to the body for the box. The box may be an opaque
331 // box. The result will be casted to the type of body_t, if it is statically
333 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
334 let _icx = push_ctxt("at_box_body");
336 let ty = Type::at_box(ccx, type_of(ccx, body_t));
337 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
338 GEPi(bcx, boxptr, [0u, abi::box_field_body])
341 // malloc_raw_dyn: allocates a box to contain a given type, but with a
342 // potentially dynamic size.
343 pub fn malloc_raw_dyn<'a>(
349 let _icx = push_ctxt("malloc_raw");
352 fn require_alloc_fn(bcx: &Block, t: ty::t, it: LangItem) -> ast::DefId {
353 let li = &bcx.tcx().lang_items;
354 match li.require(it) {
357 bcx.tcx().sess.fatal(format!("allocation of `{}` {}",
358 bcx.ty_to_str(t), s));
363 if heap == heap_exchange {
364 let llty_value = type_of::type_of(ccx, t);
367 let r = callee::trans_lang_call(
369 require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
372 rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
374 // we treat ~fn as @ here, which isn't ideal
375 let langcall = match heap {
377 require_alloc_fn(bcx, t, MallocFnLangItem)
379 heap_exchange_closure => {
380 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem)
382 _ => fail!("heap_exchange already handled")
385 // Grab the TypeRef type of box_ptr_ty.
386 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
387 let llty = type_of(ccx, box_ptr_ty);
388 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
391 let drop_glue = glue::get_drop_glue(ccx, t);
392 let r = callee::trans_lang_call(
395 [PointerCast(bcx, drop_glue, Type::glue_fn(Type::i8p()).ptr_to()), size, llalign],
397 rslt(r.bcx, PointerCast(r.bcx, r.val, llty))
401 // malloc_raw: expects an unboxed type and returns a pointer to
402 // enough space for a box of that type. This includes a rust_opaque_box
404 pub fn malloc_raw<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
406 let ty = type_of(bcx.ccx(), t);
407 let size = llsize_of(bcx.ccx(), ty);
408 malloc_raw_dyn(bcx, t, heap, size)
411 pub struct MallocResult<'a> {
417 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a smart
418 // pointer, and pulls out the body
419 pub fn malloc_general_dyn<'a>(
424 -> MallocResult<'a> {
425 assert!(heap != heap_exchange);
426 let _icx = push_ctxt("malloc_general");
427 let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
428 let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
437 pub fn malloc_general<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
438 -> MallocResult<'a> {
439 let ty = type_of(bcx.ccx(), t);
440 assert!(heap != heap_exchange);
441 malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
444 // Type descriptor and type glue stuff
446 pub fn get_tydesc_simple(ccx: &CrateContext, t: ty::t) -> ValueRef {
447 get_tydesc(ccx, t).tydesc
450 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info {
452 let tydescs = ccx.tydescs.borrow();
453 match tydescs.get().find(&t) {
454 Some(&inf) => return inf,
459 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
460 let inf = glue::declare_tydesc(ccx, t);
462 let mut tydescs = ccx.tydescs.borrow_mut();
463 tydescs.get().insert(t, inf);
467 pub fn set_optimize_for_size(f: ValueRef) {
468 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
471 pub fn set_no_inline(f: ValueRef) {
472 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
475 pub fn set_no_unwind(f: ValueRef) {
476 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
479 // Tell LLVM to emit the information necessary to unwind the stack for the
481 pub fn set_uwtable(f: ValueRef) {
482 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
485 pub fn set_inline_hint(f: ValueRef) {
486 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
489 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
491 // Set the inline hint if there is one
492 match find_inline_attr(attrs) {
493 InlineHint => set_inline_hint(llfn),
494 InlineAlways => set_always_inline(llfn),
495 InlineNever => set_no_inline(llfn),
496 InlineNone => { /* fallthrough */ }
499 // Add the no-split-stack attribute if requested
500 if contains_name(attrs, "no_split_stack") {
501 set_no_split_stack(llfn);
504 if contains_name(attrs, "cold") {
505 unsafe { llvm::LLVMAddColdAttribute(llfn) }
509 pub fn set_always_inline(f: ValueRef) {
510 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
513 pub fn set_no_split_stack(f: ValueRef) {
514 "no-split-stack".with_c_str(|buf| {
515 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
519 // Double-check that we never ask LLVM to declare the same symbol twice. It
520 // silently mangles such symbols, breaking our linkage model.
521 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
522 let mut all_llvm_symbols = ccx.all_llvm_symbols.borrow_mut();
523 if all_llvm_symbols.get().contains(&sym) {
524 ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
526 all_llvm_symbols.get().insert(sym);
530 pub fn get_res_dtor(ccx: @CrateContext,
532 parent_id: ast::DefId,
535 let _icx = push_ctxt("trans_res_dtor");
536 let did = if did.krate != ast::LOCAL_CRATE {
537 inline::maybe_instantiate_inline(ccx, did)
541 if !substs.is_empty() {
542 assert_eq!(did.krate, ast::LOCAL_CRATE);
543 let tsubsts = ty::substs {
544 regions: ty::ErasedRegions,
546 tps: substs.to_owned()
549 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx, did.node, &tsubsts);
550 let (val, _) = monomorphize::monomorphic_fn(ccx, did, &tsubsts, vtables, None, None);
553 } else if did.krate == ast::LOCAL_CRATE {
554 get_item_val(ccx, did.node)
557 let name = csearch::get_symbol(ccx.sess.cstore, did);
558 let class_ty = ty::subst_tps(tcx,
561 ty::lookup_item_type(tcx, parent_id).ty);
562 let llty = type_of_dtor(ccx, class_ty);
565 let mut externs = ccx.externs.borrow_mut();
566 get_extern_fn(externs.get(), ccx.llmod, name,
567 lib::llvm::CCallConv, llty, ty::mk_nil())
572 // Structural comparison: a rather involved form of glue.
573 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
574 if cx.sess.opts.cg.save_temps {
577 llvm::LLVMSetValueName(v, buf)
584 // Used only for creating scalar comparison glue.
585 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
587 // NB: This produces an i1, not a Rust bool (i8).
588 pub fn compare_scalar_types<'a>(
595 let f = |a| rslt(cx, compare_scalar_values(cx, lhs, rhs, a, op));
597 match ty::get(t).sty {
598 ty::ty_nil => f(nil_type),
599 ty::ty_bool | ty::ty_ptr(_) |
600 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
601 ty::ty_int(_) => f(signed_int),
602 ty::ty_float(_) => f(floating_point),
603 // Should never get here, because t is scalar.
604 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
609 // A helper function to do the actual comparison of scalar values.
610 pub fn compare_scalar_values<'a>(
617 let _icx = push_ctxt("compare_scalar_values");
618 fn die(cx: &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<'r,'b> =
673 'r |&'b Block<'b>, ValueRef, ty::t| -> &'b Block<'b>;
675 pub fn load_inbounds<'a>(cx: &'a Block<'a>, p: ValueRef, idxs: &[uint])
677 return Load(cx, GEPi(cx, p, idxs));
680 pub fn store_inbounds<'a>(
685 Store(cx, v, GEPi(cx, p, idxs));
688 // Iterates through the elements of a structural type.
689 pub fn iter_structural_ty<'r,
694 f: val_and_ty_fn<'r,'b>)
696 let _icx = push_ctxt("iter_structural_ty");
703 variant: @ty::VariantInfo,
705 f: val_and_ty_fn<'r,'b>)
707 let _icx = push_ctxt("iter_variant");
711 for (i, &arg) in variant.args.iter().enumerate() {
713 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
714 ty::subst_tps(tcx, tps, None, arg));
720 match ty::get(t).sty {
721 ty::ty_struct(..) => {
722 let repr = adt::represent_type(cx.ccx(), t);
723 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
724 for (i, field_ty) in field_tys.iter().enumerate() {
725 let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
726 cx = f(cx, llfld_a, field_ty.mt.ty);
730 ty::ty_str(ty::vstore_fixed(_)) |
731 ty::ty_vec(_, ty::vstore_fixed(_)) => {
732 let (base, len) = tvec::get_base_and_byte_len(cx, av, t);
733 cx = tvec::iter_vec_raw(cx, base, t, len, f);
735 ty::ty_tup(ref args) => {
736 let repr = adt::represent_type(cx.ccx(), t);
737 for (i, arg) in args.iter().enumerate() {
738 let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
739 cx = f(cx, llfld_a, *arg);
742 ty::ty_enum(tid, ref substs) => {
746 let repr = adt::represent_type(ccx, t);
747 let variants = ty::enum_variants(ccx.tcx, tid);
748 let n_variants = (*variants).len();
750 // NB: we must hit the discriminant first so that structural
751 // comparison know not to proceed when the discriminants differ.
753 match adt::trans_switch(cx, repr, av) {
754 (_match::single, None) => {
755 cx = iter_variant(cx, repr, av, variants[0],
758 (_match::switch, Some(lldiscrim_a)) => {
759 cx = f(cx, lldiscrim_a, ty::mk_int());
760 let unr_cx = fcx.new_temp_block("enum-iter-unr");
762 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
764 let next_cx = fcx.new_temp_block("enum-iter-next");
766 for variant in (*variants).iter() {
768 fcx.new_temp_block(~"enum-iter-variant-" +
769 variant.disr_val.to_str());
770 match adt::trans_case(cx, repr, variant.disr_val) {
771 _match::single_result(r) => {
772 AddCase(llswitch, r.val, variant_cx.llbb)
774 _ => ccx.sess.unimpl("value from adt::trans_case \
775 in iter_structural_ty")
778 iter_variant(variant_cx, repr, av, *variant,
779 substs.tps, |x,y,z| f(x,y,z));
780 Br(variant_cx, next_cx.llbb);
784 _ => ccx.sess.unimpl("value from adt::trans_switch \
785 in iter_structural_ty")
788 _ => cx.sess().unimpl("type in iter_structural_ty")
793 pub fn cast_shift_expr_rhs<'a>(
799 cast_shift_rhs(op, lhs, rhs,
800 |a,b| Trunc(cx, a, b),
801 |a,b| ZExt(cx, a, b))
804 pub fn cast_shift_const_rhs(op: ast::BinOp,
805 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
806 cast_shift_rhs(op, lhs, rhs,
807 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
808 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
811 pub fn cast_shift_rhs(op: ast::BinOp,
814 trunc: |ValueRef, Type| -> ValueRef,
815 zext: |ValueRef, Type| -> ValueRef)
817 // Shifts may have any size int on the rhs
819 if ast_util::is_shift_binop(op) {
820 let mut rhs_llty = val_ty(rhs);
821 let mut lhs_llty = val_ty(lhs);
822 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
823 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
824 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
825 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
828 } else if lhs_sz > rhs_sz {
829 // FIXME (#1877: If shifting by negative
830 // values becomes not undefined then this is wrong.
841 pub fn fail_if_zero<'a>(
848 let text = if divrem == ast::BiDiv {
849 "attempted to divide by zero"
851 "attempted remainder with a divisor of zero"
853 let is_zero = match ty::get(rhs_t).sty {
855 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
856 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
859 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
860 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
863 cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
864 ty_to_str(cx.ccx().tcx, rhs_t));
867 with_cond(cx, is_zero, |bcx| {
868 controlflow::trans_fail(bcx, span, InternedString::new(text))
872 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
873 let name = csearch::get_symbol(ccx.sess.cstore, did);
874 match ty::get(t).sty {
875 ty::ty_bare_fn(ref fn_ty) => {
876 match fn_ty.abis.for_target(ccx.sess.targ_cfg.os,
877 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, did)
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 let mut externs = ccx.externs.borrow_mut();
886 get_extern_fn(externs.get(), ccx.llmod, name,
887 cconv, llty, fn_ty.sig.output)
891 ty::ty_closure(ref f) => {
892 get_extern_rust_fn(ccx, f.sig.inputs, f.sig.output, name, did)
895 let llty = type_of(ccx, t);
896 let mut externs = ccx.externs.borrow_mut();
897 get_extern_const(externs.get(), ccx.llmod, name, llty)
906 attributes: &[(uint, lib::llvm::Attribute)],
907 call_info: Option<NodeInfo>)
908 -> (ValueRef, &'a Block<'a>) {
909 let _icx = push_ctxt("invoke_");
910 if bcx.unreachable.get() {
911 return (C_null(Type::i8()), bcx);
914 match bcx.opt_node_id {
916 debug!("invoke at ???");
919 debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
923 if need_invoke(bcx) {
924 debug!("invoking {} at {}", llfn, bcx.llbb);
925 for &llarg in llargs.iter() {
926 debug!("arg: {}", llarg);
928 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
929 let landing_pad = bcx.fcx.get_landing_pad();
932 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
933 None => debuginfo::clear_source_location(bcx.fcx)
936 let llresult = Invoke(bcx,
942 return (llresult, normal_bcx);
944 debug!("calling {} at {}", llfn, bcx.llbb);
945 for &llarg in llargs.iter() {
946 debug!("arg: {}", llarg);
950 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
951 None => debuginfo::clear_source_location(bcx.fcx)
954 let llresult = Call(bcx, llfn, llargs, attributes);
955 return (llresult, bcx);
959 pub fn need_invoke(bcx: &Block) -> bool {
960 if bcx.ccx().sess.no_landing_pads() {
964 // Avoid using invoke if we are already inside a landing pad.
969 bcx.fcx.needs_invoke()
972 pub fn do_spill(bcx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
973 if ty::type_is_bot(t) {
974 return C_null(Type::i8p());
976 let llptr = alloc_ty(bcx, t, "");
977 Store(bcx, v, llptr);
981 // Since this function does *not* root, it is the caller's responsibility to
982 // ensure that the referent is pointed to by a root.
983 pub fn do_spill_noroot(cx: &Block, v: ValueRef) -> ValueRef {
984 let llptr = alloca(cx, val_ty(v), "");
989 pub fn spill_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
990 let _icx = push_ctxt("spill_if_immediate");
991 if type_is_immediate(cx.ccx(), t) { return do_spill(cx, v, t); }
995 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
996 let _icx = push_ctxt("load_if_immediate");
997 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
1001 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1002 match local.pat.node {
1003 ast::PatWild => true, _ => false
1007 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1010 debug!("init_local(bcx={}, local.id={:?})",
1011 bcx.to_str(), local.id);
1012 let _indenter = indenter();
1014 let _icx = push_ctxt("init_local");
1016 if ignore_lhs(bcx, local) {
1017 // Handle let _ = e; just like e;
1020 return expr::trans_into(bcx, init, expr::Ignore);
1022 None => { return bcx; }
1026 _match::store_local(bcx, local)
1029 pub fn raw_block<'a>(
1030 fcx: &'a FunctionContext<'a>,
1032 llbb: BasicBlockRef)
1034 Block::new(llbb, is_lpad, None, fcx)
1037 pub fn block_locals(b: &ast::Block, it: |@ast::Local|) {
1038 for s in b.stmts.iter() {
1040 ast::StmtDecl(d, _) => {
1042 ast::DeclLocal(ref local) => it(*local),
1043 _ => {} /* fall through */
1046 _ => {} /* fall through */
1051 pub fn with_cond<'a>(
1054 f: |&'a Block<'a>| -> &'a Block<'a>)
1056 let _icx = push_ctxt("with_cond");
1058 let next_cx = fcx.new_temp_block("next");
1059 let cond_cx = fcx.new_temp_block("cond");
1060 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1061 let after_cx = f(cond_cx);
1062 if !after_cx.terminated.get() {
1063 Br(after_cx, next_cx.llbb);
1068 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1069 let _icx = push_ctxt("call_memcpy");
1071 let key = match ccx.sess.targ_cfg.arch {
1072 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1073 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1075 let memcpy = ccx.intrinsics.get_copy(&key);
1076 let src_ptr = PointerCast(cx, src, Type::i8p());
1077 let dst_ptr = PointerCast(cx, dst, Type::i8p());
1078 let size = IntCast(cx, n_bytes, ccx.int_type);
1079 let align = C_i32(align as i32);
1080 let volatile = C_i1(false);
1081 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1084 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1085 let _icx = push_ctxt("memcpy_ty");
1086 let ccx = bcx.ccx();
1087 if ty::type_is_structural(t) {
1088 let llty = type_of::type_of(ccx, t);
1089 let llsz = llsize_of(ccx, llty);
1090 let llalign = llalign_of_min(ccx, llty);
1091 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1093 Store(bcx, Load(bcx, src), dst);
1097 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1098 if cx.unreachable.get() { return; }
1099 let _icx = push_ctxt("zero_mem");
1102 let llty = type_of::type_of(ccx, t);
1103 memzero(&B(bcx), llptr, llty);
1106 // Always use this function instead of storing a zero constant to the memory
1107 // in question. If you store a zero constant, LLVM will drown in vreg
1108 // allocation for large data structures, and the generated code will be
1109 // awful. (A telltale sign of this is large quantities of
1110 // `mov [byte ptr foo],0` in the generated code.)
1111 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1112 let _icx = push_ctxt("memzero");
1115 let intrinsic_key = match ccx.sess.targ_cfg.arch {
1116 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1117 X86_64 => "llvm.memset.p0i8.i64"
1120 let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1121 let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1122 let llzeroval = C_u8(0);
1123 let size = machine::llsize_of(ccx, ty);
1124 let align = C_i32(llalign_of_min(ccx, ty) as i32);
1125 let volatile = C_i1(false);
1126 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1129 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1130 let _icx = push_ctxt("alloc_ty");
1131 let ccx = bcx.ccx();
1132 let ty = type_of::type_of(ccx, t);
1133 assert!(!ty::type_has_params(t));
1134 let val = alloca(bcx, ty, name);
1138 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1139 alloca_maybe_zeroed(cx, ty, name, false)
1142 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1143 let _icx = push_ctxt("alloca");
1144 if cx.unreachable.get() {
1146 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1149 debuginfo::clear_source_location(cx.fcx);
1150 let p = Alloca(cx, ty, name);
1152 let b = cx.fcx.ccx.builder();
1153 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1159 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1160 let _icx = push_ctxt("arrayalloca");
1161 if cx.unreachable.get() {
1163 return llvm::LLVMGetUndef(ty.to_ref());
1166 debuginfo::clear_source_location(cx.fcx);
1167 return ArrayAlloca(cx, ty, v);
1170 pub struct BasicBlocks {
1174 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1176 let cx = task_llcx();
1177 "static_allocas".with_c_str(|buf| {
1178 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1183 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1185 let cx = task_llcx();
1186 "return".with_c_str(|buf| {
1187 llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1192 // Creates and returns space for, or returns the argument representing, the
1193 // slot where the return value of the function must go.
1194 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1197 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1198 llvm::LLVMGetParam(fcx.llfn, 0)
1200 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1201 let bcx = fcx.entry_bcx.get().unwrap();
1202 Alloca(bcx, lloutputtype, "__make_return_pointer")
1207 // NB: must keep 4 fns in sync:
1210 // - create_datums_for_fn_args.
1214 // Be warned! You must call `init_function` before doing anything with the
1215 // returned function context.
1216 pub fn new_fn_ctxt<'a>(ccx: @CrateContext,
1221 param_substs: Option<@param_substs>,
1223 block_arena: &'a TypedArena<Block<'a>>)
1224 -> FunctionContext<'a> {
1225 for p in param_substs.iter() { p.validate(); }
1227 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1228 if id == -1 { ~"" } else { ccx.tcx.map.path_to_str(id) },
1229 id, param_substs.repr(ccx.tcx));
1231 let substd_output_type = match param_substs {
1232 None => output_type,
1234 ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1237 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1238 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1240 let mut fcx = FunctionContext {
1243 llretptr: Cell::new(None),
1244 entry_bcx: RefCell::new(None),
1245 alloca_insert_pt: Cell::new(None),
1246 llreturn: Cell::new(None),
1247 personality: Cell::new(None),
1248 caller_expects_out_pointer: uses_outptr,
1249 llargs: RefCell::new(NodeMap::new()),
1250 lllocals: RefCell::new(NodeMap::new()),
1251 llupvars: RefCell::new(NodeMap::new()),
1253 param_substs: param_substs,
1255 block_arena: block_arena,
1257 debug_context: debug_context,
1258 scopes: RefCell::new(~[])
1262 fcx.llenv = Some(unsafe {
1263 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1270 /// Performs setup on a newly created function, creating the entry scope block
1271 /// and allocating space for the return pointer.
1272 pub fn init_function<'a>(
1273 fcx: &'a FunctionContext<'a>,
1276 param_substs: Option<@param_substs>) {
1277 let entry_bcx = fcx.new_temp_block("entry-block");
1279 fcx.entry_bcx.set(Some(entry_bcx));
1281 // Use a dummy instruction as the insertion point for all allocas.
1282 // This is later removed in FunctionContext::cleanup.
1283 fcx.alloca_insert_pt.set(Some(unsafe {
1284 Load(entry_bcx, C_null(Type::i8p()));
1285 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1288 let substd_output_type = match param_substs {
1289 None => output_type,
1291 ty::subst_tps(fcx.ccx.tcx,
1298 if !return_type_is_void(fcx.ccx, substd_output_type) {
1299 // If the function returns nil/bot, there is no real return
1300 // value, so do not set `llretptr`.
1301 if !skip_retptr || fcx.caller_expects_out_pointer {
1302 // Otherwise, we normally allocate the llretptr, unless we
1303 // have been instructed to skip it for immediate return
1305 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1310 // NB: must keep 4 fns in sync:
1313 // - create_datums_for_fn_args.
1317 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1318 use middle::trans::datum::{ByRef, ByValue};
1321 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1325 // work around bizarre resolve errors
1326 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1327 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1329 // create_datums_for_fn_args: creates rvalue datums for each of the
1330 // incoming function arguments. These will later be stored into
1331 // appropriate lvalue datums.
1332 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1335 let _icx = push_ctxt("create_datums_for_fn_args");
1337 // Return an array wrapping the ValueRefs that we get from
1338 // llvm::LLVMGetParam for each argument into datums.
1339 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1340 let llarg = unsafe {
1341 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1343 datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1347 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1348 arg_scope: cleanup::CustomScopeIndex,
1351 arg_datums: ~[RvalueDatum])
1353 debug!("copy_args_to_allocas");
1355 let _icx = push_ctxt("copy_args_to_allocas");
1358 let arg_scope_id = cleanup::CustomScope(arg_scope);
1360 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1361 // For certain mode/type combinations, the raw llarg values are passed
1362 // by value. However, within the fn body itself, we want to always
1363 // have all locals and arguments be by-ref so that we can cancel the
1364 // cleanup and for better interaction with LLVM's debug info. So, if
1365 // the argument would be passed by value, we store it into an alloca.
1366 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1367 // the event it's not truly needed.
1369 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1371 if fcx.ccx.sess.opts.debuginfo == FullDebugInfo {
1372 debuginfo::create_argument_metadata(bcx, &args[i]);
1379 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1380 // and builds the return block.
1381 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1382 last_bcx: &'a Block<'a>) {
1383 let _icx = push_ctxt("finish_fn");
1385 let ret_cx = match fcx.llreturn.get() {
1387 if !last_bcx.terminated.get() {
1388 Br(last_bcx, llreturn);
1390 raw_block(fcx, false, llreturn)
1394 build_return_block(fcx, ret_cx);
1395 debuginfo::clear_source_location(fcx);
1399 // Builds the return block for a function.
1400 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1401 // Return the value if this function immediate; otherwise, return void.
1402 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1403 return RetVoid(ret_cx);
1406 let retptr = Value(fcx.llretptr.get().unwrap());
1407 let retval = match retptr.get_dominating_store(ret_cx) {
1408 // If there's only a single store to the ret slot, we can directly return
1409 // the value that was stored and omit the store and the alloca
1411 let retval = s.get_operand(0).unwrap().get();
1412 s.erase_from_parent();
1414 if retptr.has_no_uses() {
1415 retptr.erase_from_parent();
1420 // Otherwise, load the return value from the ret slot
1421 None => Load(ret_cx, fcx.llretptr.get().unwrap())
1425 Ret(ret_cx, retval);
1428 // trans_closure: Builds an LLVM function out of a source function.
1429 // If the function closes over its environment a closure will be
1431 pub fn trans_closure<'a>(ccx: @CrateContext,
1435 param_substs: Option<@param_substs>,
1437 _attributes: &[ast::Attribute],
1439 maybe_load_env: <'b> |&'b Block<'b>| -> &'b Block<'b>) {
1440 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1442 let _icx = push_ctxt("trans_closure");
1443 set_uwtable(llfndecl);
1445 debug!("trans_closure(..., param_substs={})",
1446 param_substs.repr(ccx.tcx));
1448 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx, id)).sty {
1449 ty::ty_closure(_) => true,
1453 let arena = TypedArena::new();
1454 let fcx = new_fn_ctxt(ccx,
1462 init_function(&fcx, false, output_type, param_substs);
1464 // cleanup scope for the incoming arguments
1465 let arg_scope = fcx.push_custom_cleanup_scope();
1467 // Create the first basic block in the function and keep a handle on it to
1468 // pass to finish_fn later.
1469 let bcx_top = fcx.entry_bcx.get().unwrap();
1470 let mut bcx = bcx_top;
1471 let block_ty = node_id_type(bcx, body.id);
1473 // Set up arguments to the function.
1474 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1475 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys);
1477 bcx = copy_args_to_allocas(&fcx,
1480 decl.inputs.as_slice(),
1483 bcx = maybe_load_env(bcx);
1485 // Up until here, IR instructions for this function have explicitly not been annotated with
1486 // source code location, so we don't step into call setup code. From here on, source location
1487 // emitting should be enabled.
1488 debuginfo::start_emitting_source_locations(&fcx);
1490 let dest = match fcx.llretptr.get() {
1491 Some(e) => {expr::SaveIn(e)}
1493 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1498 // This call to trans_block is the place where we bridge between
1499 // translation calls that don't have a return value (trans_crate,
1500 // trans_mod, trans_item, et cetera) and those that do
1501 // (trans_block, trans_expr, et cetera).
1502 bcx = controlflow::trans_block(bcx, body, dest);
1504 match fcx.llreturn.get() {
1506 Br(bcx, fcx.return_exit_block());
1507 fcx.pop_custom_cleanup_scope(arg_scope);
1510 // Microoptimization writ large: avoid creating a separate
1511 // llreturn basic block
1512 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1516 // Put return block after all other blocks.
1517 // This somewhat improves single-stepping experience in debugger.
1519 let llreturn = fcx.llreturn.get();
1520 for &llreturn in llreturn.iter() {
1521 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1525 // Insert the mandatory first few basic blocks before lltop.
1526 finish_fn(&fcx, bcx);
1529 // trans_fn: creates an LLVM function corresponding to a source language
1531 pub fn trans_fn(ccx: @CrateContext,
1535 param_substs: Option<@param_substs>,
1537 attrs: &[ast::Attribute]) {
1538 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id));
1539 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx));
1540 let _icx = push_ctxt("trans_fn");
1541 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1542 trans_closure(ccx, decl, body, llfndecl,
1543 param_substs, id, attrs, output_type, |bcx| bcx);
1546 pub fn trans_enum_variant(ccx: @CrateContext,
1547 _enum_id: ast::NodeId,
1548 variant: &ast::Variant,
1549 _args: &[ast::VariantArg],
1551 param_substs: Option<@param_substs>,
1552 llfndecl: ValueRef) {
1553 let _icx = push_ctxt("trans_enum_variant");
1555 trans_enum_variant_or_tuple_like_struct(
1563 pub fn trans_tuple_struct(ccx: @CrateContext,
1564 _fields: &[ast::StructField],
1565 ctor_id: ast::NodeId,
1566 param_substs: Option<@param_substs>,
1567 llfndecl: ValueRef) {
1568 let _icx = push_ctxt("trans_tuple_struct");
1570 trans_enum_variant_or_tuple_like_struct(
1578 fn trans_enum_variant_or_tuple_like_struct(ccx: @CrateContext,
1579 ctor_id: ast::NodeId,
1581 param_substs: Option<@param_substs>,
1582 llfndecl: ValueRef) {
1583 let no_substs: &[ty::t] = [];
1584 let ty_param_substs = match param_substs {
1585 Some(ref substs) => {
1586 let v: &[ty::t] = substs.tys;
1590 let v: &[ty::t] = no_substs;
1595 let ctor_ty = ty::subst_tps(ccx.tcx,
1598 ty::node_id_to_type(ccx.tcx, ctor_id));
1600 let result_ty = match ty::get(ctor_ty).sty {
1601 ty::ty_bare_fn(ref bft) => bft.sig.output,
1603 format!("trans_enum_variant_or_tuple_like_struct: \
1604 unexpected ctor return type {}",
1605 ty_to_str(ccx.tcx, ctor_ty)))
1608 let arena = TypedArena::new();
1609 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1610 param_substs, None, &arena);
1611 init_function(&fcx, false, result_ty, param_substs);
1613 let arg_tys = ty::ty_fn_args(ctor_ty);
1615 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys);
1617 let bcx = fcx.entry_bcx.get().unwrap();
1619 if !type_is_zero_size(fcx.ccx, result_ty) {
1620 let repr = adt::represent_type(ccx, result_ty);
1621 adt::trans_start_init(bcx, repr, fcx.llretptr.get().unwrap(), disr);
1622 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1623 let lldestptr = adt::trans_field_ptr(bcx,
1625 fcx.llretptr.get().unwrap(),
1628 arg_datum.store_to(bcx, lldestptr);
1632 finish_fn(&fcx, bcx);
1635 pub fn trans_enum_def(ccx: @CrateContext, enum_definition: &ast::EnumDef,
1636 id: ast::NodeId, vi: @~[@ty::VariantInfo],
1638 for &variant in enum_definition.variants.iter() {
1639 let disr_val = vi[*i].disr_val;
1642 match variant.node.kind {
1643 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1644 let llfn = get_item_val(ccx, variant.node.id);
1645 trans_enum_variant(ccx, id, variant, args.as_slice(),
1646 disr_val, None, llfn);
1648 ast::TupleVariantKind(_) => {
1651 ast::StructVariantKind(struct_def) => {
1652 trans_struct_def(ccx, struct_def);
1658 pub struct TransItemVisitor {
1662 impl Visitor<()> for TransItemVisitor {
1663 fn visit_item(&mut self, i: &ast::Item, _:()) {
1664 trans_item(self.ccx, i);
1668 pub fn trans_item(ccx: @CrateContext, item: &ast::Item) {
1669 let _icx = push_ctxt("trans_item");
1671 ast::ItemFn(decl, purity, _abis, ref generics, body) => {
1672 if purity == ast::ExternFn {
1673 let llfndecl = get_item_val(ccx, item.id);
1674 foreign::trans_rust_fn_with_foreign_abi(
1675 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1676 } else if !generics.is_type_parameterized() {
1677 let llfn = get_item_val(ccx, item.id);
1684 item.attrs.as_slice());
1686 // Be sure to travel more than just one layer deep to catch nested
1687 // items in blocks and such.
1688 let mut v = TransItemVisitor{ ccx: ccx };
1689 v.visit_block(body, ());
1692 ast::ItemImpl(ref generics, _, _, ref ms) => {
1693 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1695 ast::ItemMod(ref m) => {
1698 ast::ItemEnum(ref enum_definition, ref generics) => {
1699 if !generics.is_type_parameterized() {
1700 let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
1702 trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
1705 ast::ItemStatic(_, m, expr) => {
1706 consts::trans_const(ccx, m, item.id);
1707 // Do static_assert checking. It can't really be done much earlier
1708 // because we need to get the value of the bool out of LLVM
1709 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1710 if m == ast::MutMutable {
1711 ccx.sess.span_fatal(expr.span,
1712 "cannot have static_assert on a mutable \
1716 let const_values = ccx.const_values.borrow();
1717 let v = const_values.get().get_copy(&item.id);
1719 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1720 ccx.sess.span_fatal(expr.span, "static assertion failed");
1725 ast::ItemForeignMod(ref foreign_mod) => {
1726 foreign::trans_foreign_mod(ccx, foreign_mod);
1728 ast::ItemStruct(struct_def, ref generics) => {
1729 if !generics.is_type_parameterized() {
1730 trans_struct_def(ccx, struct_def);
1733 ast::ItemTrait(..) => {
1734 // Inside of this trait definition, we won't be actually translating any
1735 // functions, but the trait still needs to be walked. Otherwise default
1736 // methods with items will not get translated and will cause ICE's when
1737 // metadata time comes around.
1738 let mut v = TransItemVisitor{ ccx: ccx };
1739 visit::walk_item(&mut v, item, ());
1741 _ => {/* fall through */ }
1745 pub fn trans_struct_def(ccx: @CrateContext, struct_def: @ast::StructDef) {
1746 // If this is a tuple-like struct, translate the constructor.
1747 match struct_def.ctor_id {
1748 // We only need to translate a constructor if there are fields;
1749 // otherwise this is a unit-like struct.
1750 Some(ctor_id) if struct_def.fields.len() > 0 => {
1751 let llfndecl = get_item_val(ccx, ctor_id);
1752 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1753 ctor_id, None, llfndecl);
1755 Some(_) | None => {}
1759 // Translate a module. Doing this amounts to translating the items in the
1760 // module; there ends up being no artifact (aside from linkage names) of
1761 // separate modules in the compiled program. That's because modules exist
1762 // only as a convenience for humans working with the code, to organize names
1763 // and control visibility.
1764 pub fn trans_mod(ccx: @CrateContext, m: &ast::Mod) {
1765 let _icx = push_ctxt("trans_mod");
1766 for item in m.items.iter() {
1767 trans_item(ccx, *item);
1771 fn finish_register_fn(ccx: @CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1774 let mut item_symbols = ccx.item_symbols.borrow_mut();
1775 item_symbols.get().insert(node_id, sym);
1779 let reachable = ccx.reachable.borrow();
1780 if !reachable.get().contains(&node_id) {
1781 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1785 if is_entry_fn(&ccx.sess, node_id) && !ccx.sess.building_library.get() {
1786 create_entry_wrapper(ccx, sp, llfn);
1790 fn register_fn(ccx: @CrateContext,
1793 node_id: ast::NodeId,
1796 let f = match ty::get(node_type).sty {
1797 ty::ty_bare_fn(ref f) => {
1798 assert!(f.abis.is_rust() || f.abis.is_intrinsic());
1801 _ => fail!("expected bare rust fn or an intrinsic")
1804 let llfn = decl_rust_fn(ccx, false, f.sig.inputs, f.sig.output, sym);
1805 finish_register_fn(ccx, sp, sym, node_id, llfn);
1809 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1810 pub fn register_fn_llvmty(ccx: @CrateContext,
1813 node_id: ast::NodeId,
1814 cc: lib::llvm::CallConv,
1816 output: ty::t) -> ValueRef {
1817 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1819 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1820 finish_register_fn(ccx, sp, sym, node_id, llfn);
1824 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1825 match sess.entry_fn.get() {
1826 Some((entry_id, _)) => node_id == entry_id,
1831 // Create a _rust_main(args: ~[str]) function which will be called from the
1832 // runtime rust_start function
1833 pub fn create_entry_wrapper(ccx: @CrateContext,
1835 main_llfn: ValueRef) {
1836 let et = ccx.sess.entry_type.get().unwrap();
1838 session::EntryMain => {
1839 create_entry_fn(ccx, main_llfn, true);
1841 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1842 session::EntryNone => {} // Do nothing.
1845 fn create_entry_fn(ccx: @CrateContext,
1846 rust_main: ValueRef,
1847 use_start_lang_item: bool) {
1848 let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
1851 let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1852 let llbb = "top".with_c_str(|buf| {
1854 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1857 let bld = ccx.builder.b;
1859 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1861 let (start_fn, args) = if use_start_lang_item {
1862 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1864 Err(s) => { ccx.tcx.sess.fatal(s); }
1866 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1867 get_item_val(ccx, start_def_id.node)
1869 let start_fn_type = csearch::get_type(ccx.tcx,
1871 trans_external_path(ccx, start_def_id, start_fn_type)
1875 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1876 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
1881 llvm::LLVMGetParam(llfn, 0),
1882 llvm::LLVMGetParam(llfn, 1)
1887 debug!("using user-defined start fn");
1889 llvm::LLVMGetParam(llfn, 0 as c_uint),
1890 llvm::LLVMGetParam(llfn, 1 as c_uint)
1896 let result = llvm::LLVMBuildCall(bld, start_fn,
1897 args.as_ptr(), args.len() as c_uint,
1900 llvm::LLVMBuildRet(bld, result);
1905 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1906 ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1907 match attr::first_attr_value_str_by_name(attrs, "export_name") {
1908 // Use provided name
1909 Some(name) => name.get().to_owned(),
1911 _ => ccx.tcx.map.with_path(id, |mut path| {
1912 if attr::contains_name(attrs, "no_mangle") {
1914 path.last().unwrap().to_str()
1916 // Usual name mangling
1917 mangle_exported_name(ccx, path, ty, id)
1923 pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
1924 debug!("get_item_val(id=`{:?}`)", id);
1927 let item_vals = ccx.item_vals.borrow();
1928 item_vals.get().find_copy(&id)
1934 let mut foreign = false;
1935 let item = ccx.tcx.map.get(id);
1936 let val = match item {
1937 ast_map::NodeItem(i) => {
1938 let ty = ty::node_id_to_type(ccx.tcx, i.id);
1939 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1941 let v = match i.node {
1942 ast::ItemStatic(_, _, expr) => {
1943 // If this static came from an external crate, then
1944 // we need to get the symbol from csearch instead of
1945 // using the current crate's name/version
1946 // information in the hash of the symbol
1947 debug!("making {}", sym);
1948 let (sym, is_local) = {
1949 let external_srcs = ccx.external_srcs
1951 match external_srcs.get().find(&i.id) {
1953 debug!("but found in other crate...");
1954 (csearch::get_symbol(ccx.sess.cstore,
1961 // We need the translated value here, because for enums the
1962 // LLVM type is not fully determined by the Rust type.
1963 let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1965 let mut const_values = ccx.const_values
1967 const_values.get().insert(id, v);
1969 let mut inlineable = inlineable;
1972 let llty = llvm::LLVMTypeOf(v);
1973 let g = sym.with_c_str(|buf| {
1974 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1978 let reachable = ccx.reachable.borrow();
1979 if !reachable.get().contains(&id) {
1980 lib::llvm::SetLinkage(
1982 lib::llvm::InternalLinkage);
1986 // Apply the `unnamed_addr` attribute if
1988 if attr::contains_name(i.attrs.as_slice(),
1989 "address_insignificant"){
1992 ccx.reachable.borrow();
1993 if reachable.get().contains(&id) {
1994 ccx.sess.span_bug(i.span,
1995 "insignificant static is \
1999 lib::llvm::SetUnnamedAddr(g, true);
2001 // This is a curious case where we must make
2002 // all of these statics inlineable. If a
2003 // global is tagged as
2004 // address_insignificant, then LLVM won't
2005 // coalesce globals unless they have an
2006 // internal linkage type. This means that
2007 // external crates cannot use this global.
2008 // This is a problem for things like inner
2009 // statics in generic functions, because the
2010 // function will be inlined into another
2011 // crate and then attempt to link to the
2012 // static in the original crate, only to
2013 // find that it's not there. On the other
2014 // side of inlininig, the crates knows to
2015 // not declare this static as
2016 // available_externally (because it isn't)
2020 if attr::contains_name(i.attrs.as_slice(),
2022 lib::llvm::set_thread_local(g, true);
2026 debug!("{} not inlined", sym);
2027 let mut non_inlineable_statics =
2028 ccx.non_inlineable_statics
2030 non_inlineable_statics.get().insert(id);
2033 let mut item_symbols = ccx.item_symbols
2035 item_symbols.get().insert(i.id, sym);
2040 ast::ItemFn(_, purity, _, _, _) => {
2041 let llfn = if purity != ast::ExternFn {
2042 register_fn(ccx, i.span, sym, i.id, ty)
2044 foreign::register_rust_fn_with_foreign_abi(ccx,
2049 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2053 _ => fail!("get_item_val: weird result in table")
2056 match attr::first_attr_value_str_by_name(i.attrs
2059 Some(sect) => unsafe {
2060 sect.get().with_c_str(|buf| {
2061 llvm::LLVMSetSection(v, buf);
2070 ast_map::NodeTraitMethod(trait_method) => {
2071 debug!("get_item_val(): processing a NodeTraitMethod");
2072 match *trait_method {
2073 ast::Required(_) => {
2074 ccx.sess.bug("unexpected variant: required trait method in \
2077 ast::Provided(m) => {
2078 register_method(ccx, id, m)
2083 ast_map::NodeMethod(m) => {
2084 register_method(ccx, id, m)
2087 ast_map::NodeForeignItem(ni) => {
2088 let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2092 ast::ForeignItemFn(..) => {
2093 let abis = ccx.tcx.map.get_foreign_abis(id);
2094 foreign::register_foreign_item_fn(ccx, abis, ni)
2096 ast::ForeignItemStatic(..) => {
2097 // Treat the crate map static specially in order to
2098 // a weak-linkage-like functionality where it's
2099 // dynamically resolved at runtime. If we're
2100 // building a library, then we declare the static
2101 // with weak linkage, but if we're building a
2102 // library then we've already declared the crate map
2103 // so use that instead.
2104 if attr::contains_name(ni.attrs.as_slice(),
2106 if ccx.sess.building_library.get() {
2107 let s = "_rust_crate_map_toplevel";
2109 s.with_c_str(|buf| {
2110 let ty = type_of(ccx, ty);
2111 llvm::LLVMAddGlobal(ccx.llmod,
2116 lib::llvm::SetLinkage(g,
2117 lib::llvm::ExternalWeakLinkage);
2123 let ident = foreign::link_name(ni);
2125 ident.get().with_c_str(|buf| {
2126 let ty = type_of(ccx, ty);
2127 llvm::LLVMAddGlobal(ccx.llmod,
2136 ast_map::NodeVariant(ref v) => {
2139 ast::TupleVariantKind(ref args) => {
2140 assert!(args.len() != 0u);
2141 let ty = ty::node_id_to_type(ccx.tcx, id);
2142 let parent = ccx.tcx.map.get_parent(id);
2143 let enm = ccx.tcx.map.expect_item(parent);
2144 let sym = exported_name(ccx,
2147 enm.attrs.as_slice());
2149 llfn = match enm.node {
2150 ast::ItemEnum(_, _) => {
2151 register_fn(ccx, (*v).span, sym, id, ty)
2153 _ => fail!("NodeVariant, shouldn't happen")
2156 ast::StructVariantKind(_) => {
2157 fail!("struct variant kind unexpected in get_item_val")
2160 set_inline_hint(llfn);
2164 ast_map::NodeStructCtor(struct_def) => {
2165 // Only register the constructor if this is a tuple-like struct.
2166 match struct_def.ctor_id {
2168 ccx.tcx.sess.bug("attempt to register a constructor of \
2169 a non-tuple-like struct")
2172 let parent = ccx.tcx.map.get_parent(id);
2173 let struct_item = ccx.tcx.map.expect_item(parent);
2174 let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2175 let sym = exported_name(ccx,
2180 let llfn = register_fn(ccx, struct_item.span,
2182 set_inline_hint(llfn);
2189 ccx.sess.bug(format!("get_item_val(): unexpected variant: {:?}",
2194 // foreign items (extern fns and extern statics) don't have internal
2195 // linkage b/c that doesn't quite make sense. Otherwise items can
2196 // have internal linkage if they're not reachable.
2198 let reachable = ccx.reachable.borrow();
2199 if !foreign && !reachable.get().contains(&id) {
2200 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2204 let mut item_vals = ccx.item_vals.borrow_mut();
2205 item_vals.get().insert(id, val);
2211 fn register_method(ccx: @CrateContext, id: ast::NodeId,
2212 m: &ast::Method) -> ValueRef {
2213 let mty = ty::node_id_to_type(ccx.tcx, id);
2215 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2217 let llfn = register_fn(ccx, m.span, sym, id, mty);
2218 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2222 pub fn vp2i(cx: &Block, v: ValueRef) -> ValueRef {
2224 return PtrToInt(cx, v, ccx.int_type);
2227 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2229 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2234 ($intrinsics:ident, $name:expr, $args:expr, $ret:expr) => ({
2236 // HACK(eddyb) dummy output type, shouln't affect anything.
2237 let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret), ty::mk_nil());
2238 $intrinsics.insert(name, f);
2242 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2243 let i8p = Type::i8p();
2244 let mut intrinsics = HashMap::new();
2246 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i32",
2247 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2248 ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i64",
2249 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2250 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i32",
2251 [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2252 ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i64",
2253 [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2254 ifn!(intrinsics, "llvm.memset.p0i8.i32",
2255 [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2256 ifn!(intrinsics, "llvm.memset.p0i8.i64",
2257 [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2259 ifn!(intrinsics, "llvm.trap", [], Type::void());
2260 ifn!(intrinsics, "llvm.debugtrap", [], Type::void());
2261 ifn!(intrinsics, "llvm.frameaddress", [Type::i32()], i8p);
2263 ifn!(intrinsics, "llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2264 ifn!(intrinsics, "llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2265 ifn!(intrinsics, "llvm.pow.f32", [Type::f32(), Type::f32()], Type::f32());
2266 ifn!(intrinsics, "llvm.pow.f64", [Type::f64(), Type::f64()], Type::f64());
2268 ifn!(intrinsics, "llvm.sqrt.f32", [Type::f32()], Type::f32());
2269 ifn!(intrinsics, "llvm.sqrt.f64", [Type::f64()], Type::f64());
2270 ifn!(intrinsics, "llvm.sin.f32", [Type::f32()], Type::f32());
2271 ifn!(intrinsics, "llvm.sin.f64", [Type::f64()], Type::f64());
2272 ifn!(intrinsics, "llvm.cos.f32", [Type::f32()], Type::f32());
2273 ifn!(intrinsics, "llvm.cos.f64", [Type::f64()], Type::f64());
2274 ifn!(intrinsics, "llvm.exp.f32", [Type::f32()], Type::f32());
2275 ifn!(intrinsics, "llvm.exp.f64", [Type::f64()], Type::f64());
2276 ifn!(intrinsics, "llvm.exp2.f32", [Type::f32()], Type::f32());
2277 ifn!(intrinsics, "llvm.exp2.f64", [Type::f64()], Type::f64());
2278 ifn!(intrinsics, "llvm.log.f32", [Type::f32()], Type::f32());
2279 ifn!(intrinsics, "llvm.log.f64", [Type::f64()], Type::f64());
2280 ifn!(intrinsics, "llvm.log10.f32",[Type::f32()], Type::f32());
2281 ifn!(intrinsics, "llvm.log10.f64",[Type::f64()], Type::f64());
2282 ifn!(intrinsics, "llvm.log2.f32", [Type::f32()], Type::f32());
2283 ifn!(intrinsics, "llvm.log2.f64", [Type::f64()], Type::f64());
2285 ifn!(intrinsics, "llvm.fma.f32", [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2286 ifn!(intrinsics, "llvm.fma.f64", [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2288 ifn!(intrinsics, "llvm.fabs.f32", [Type::f32()], Type::f32());
2289 ifn!(intrinsics, "llvm.fabs.f64", [Type::f64()], Type::f64());
2291 ifn!(intrinsics, "llvm.floor.f32",[Type::f32()], Type::f32());
2292 ifn!(intrinsics, "llvm.floor.f64",[Type::f64()], Type::f64());
2293 ifn!(intrinsics, "llvm.ceil.f32", [Type::f32()], Type::f32());
2294 ifn!(intrinsics, "llvm.ceil.f64", [Type::f64()], Type::f64());
2295 ifn!(intrinsics, "llvm.trunc.f32",[Type::f32()], Type::f32());
2296 ifn!(intrinsics, "llvm.trunc.f64",[Type::f64()], Type::f64());
2298 ifn!(intrinsics, "llvm.rint.f32", [Type::f32()], Type::f32());
2299 ifn!(intrinsics, "llvm.rint.f64", [Type::f64()], Type::f64());
2300 ifn!(intrinsics, "llvm.nearbyint.f32", [Type::f32()], Type::f32());
2301 ifn!(intrinsics, "llvm.nearbyint.f64", [Type::f64()], Type::f64());
2303 ifn!(intrinsics, "llvm.ctpop.i8", [Type::i8()], Type::i8());
2304 ifn!(intrinsics, "llvm.ctpop.i16",[Type::i16()], Type::i16());
2305 ifn!(intrinsics, "llvm.ctpop.i32",[Type::i32()], Type::i32());
2306 ifn!(intrinsics, "llvm.ctpop.i64",[Type::i64()], Type::i64());
2308 ifn!(intrinsics, "llvm.ctlz.i8", [Type::i8() , Type::i1()], Type::i8());
2309 ifn!(intrinsics, "llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2310 ifn!(intrinsics, "llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2311 ifn!(intrinsics, "llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2313 ifn!(intrinsics, "llvm.cttz.i8", [Type::i8() , Type::i1()], Type::i8());
2314 ifn!(intrinsics, "llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2315 ifn!(intrinsics, "llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2316 ifn!(intrinsics, "llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2318 ifn!(intrinsics, "llvm.bswap.i16",[Type::i16()], Type::i16());
2319 ifn!(intrinsics, "llvm.bswap.i32",[Type::i32()], Type::i32());
2320 ifn!(intrinsics, "llvm.bswap.i64",[Type::i64()], Type::i64());
2322 ifn!(intrinsics, "llvm.sadd.with.overflow.i8",
2323 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2324 ifn!(intrinsics, "llvm.sadd.with.overflow.i16",
2325 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2326 ifn!(intrinsics, "llvm.sadd.with.overflow.i32",
2327 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2328 ifn!(intrinsics, "llvm.sadd.with.overflow.i64",
2329 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2331 ifn!(intrinsics, "llvm.uadd.with.overflow.i8",
2332 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2333 ifn!(intrinsics, "llvm.uadd.with.overflow.i16",
2334 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2335 ifn!(intrinsics, "llvm.uadd.with.overflow.i32",
2336 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2337 ifn!(intrinsics, "llvm.uadd.with.overflow.i64",
2338 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2340 ifn!(intrinsics, "llvm.ssub.with.overflow.i8",
2341 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2342 ifn!(intrinsics, "llvm.ssub.with.overflow.i16",
2343 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2344 ifn!(intrinsics, "llvm.ssub.with.overflow.i32",
2345 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2346 ifn!(intrinsics, "llvm.ssub.with.overflow.i64",
2347 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2349 ifn!(intrinsics, "llvm.usub.with.overflow.i8",
2350 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2351 ifn!(intrinsics, "llvm.usub.with.overflow.i16",
2352 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2353 ifn!(intrinsics, "llvm.usub.with.overflow.i32",
2354 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2355 ifn!(intrinsics, "llvm.usub.with.overflow.i64",
2356 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2358 ifn!(intrinsics, "llvm.smul.with.overflow.i8",
2359 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2360 ifn!(intrinsics, "llvm.smul.with.overflow.i16",
2361 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2362 ifn!(intrinsics, "llvm.smul.with.overflow.i32",
2363 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2364 ifn!(intrinsics, "llvm.smul.with.overflow.i64",
2365 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2367 ifn!(intrinsics, "llvm.umul.with.overflow.i8",
2368 [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2369 ifn!(intrinsics, "llvm.umul.with.overflow.i16",
2370 [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2371 ifn!(intrinsics, "llvm.umul.with.overflow.i32",
2372 [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2373 ifn!(intrinsics, "llvm.umul.with.overflow.i64",
2374 [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2376 ifn!(intrinsics, "llvm.expect.i1", [Type::i1(), Type::i1()], Type::i1());
2378 // Some intrinsics were introduced in later versions of LLVM, but they have
2379 // fallbacks in libc or libm and such. Currently, all of these intrinsics
2380 // were introduced in LLVM 3.4, so we case on that.
2381 macro_rules! compatible_ifn (
2382 ($intrinsics:ident, $name:expr, $cname:expr, $args:expr, $ret:expr) => ({
2384 if unsafe { llvm::LLVMVersionMinor() >= 4 } {
2385 ifn!($intrinsics, $name, $args, $ret);
2387 let f = decl_cdecl_fn(llmod, $cname,
2388 Type::func($args, &$ret),
2390 $intrinsics.insert(name, f);
2395 compatible_ifn!(intrinsics, "llvm.copysign.f32", "copysignf",
2396 [Type::f32(), Type::f32()], Type::f32());
2397 compatible_ifn!(intrinsics, "llvm.copysign.f64", "copysign",
2398 [Type::f64(), Type::f64()], Type::f64());
2399 compatible_ifn!(intrinsics, "llvm.round.f32", "roundf",
2400 [Type::f32()], Type::f32());
2401 compatible_ifn!(intrinsics, "llvm.round.f64", "round",
2402 [Type::f64()], Type::f64());
2407 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2408 ifn!(intrinsics, "llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2410 "llvm.dbg.value", [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2413 pub fn trap(bcx: &Block) {
2414 match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2415 Some(&x) => { Call(bcx, x, [], []); },
2416 _ => bcx.sess().bug("unbound llvm.trap in trap")
2420 pub fn decl_gc_metadata(ccx: &CrateContext, llmod_id: &str) {
2421 if !ccx.sess.opts.gc || !ccx.uses_gc {
2425 let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2426 let gc_metadata = gc_metadata_name.with_c_str(|buf| {
2428 llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2432 llvm::LLVMSetGlobalConstant(gc_metadata, True);
2433 lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2435 let mut module_data = ccx.module_data.borrow_mut();
2436 module_data.get().insert(~"_gc_module_metadata", gc_metadata);
2440 pub fn create_module_map(ccx: &CrateContext) -> (ValueRef, uint) {
2441 let str_slice_type = Type::struct_([Type::i8p(), ccx.int_type], false);
2442 let elttype = Type::struct_([str_slice_type, ccx.int_type], false);
2444 let module_data = ccx.module_data.borrow();
2445 Type::array(&elttype, module_data.get().len() as u64)
2447 let map = "_rust_mod_map".with_c_str(|buf| {
2449 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2452 lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2453 let mut elts: ~[ValueRef] = ~[];
2455 // This is not ideal, but the borrow checker doesn't
2456 // like the multiple borrows. At least, it doesn't
2457 // like them on the current snapshot. (2013-06-14)
2460 let module_data = ccx.module_data.borrow();
2461 for (k, _) in module_data.get().iter() {
2462 keys.push(k.clone());
2467 for key in keys.iter() {
2468 let llstrval = C_str_slice(ccx, token::intern_and_get_ident(*key));
2469 let module_data = ccx.module_data.borrow();
2470 let val = *module_data.get().find_equiv(key).unwrap();
2471 let v_ptr = p2i(ccx, val);
2472 let elt = C_struct([
2479 llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2481 return (map, keys.len())
2484 pub fn symname(name: &str, hash: &str, vers: &str) -> ~str {
2485 let path = [PathName(token::intern(name))];
2486 link::exported_name(ast_map::Values(path.iter()).chain(None), hash, vers)
2489 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2490 llmod: ModuleRef) -> (~str, ValueRef) {
2491 let targ_cfg = sess.targ_cfg;
2492 let int_type = Type::int(targ_cfg.arch);
2493 let mut n_subcrates = 1;
2494 let cstore = sess.cstore;
2495 while cstore.have_crate_data(n_subcrates) { n_subcrates += 1; }
2496 let is_top = !sess.building_library.get() || sess.opts.cg.gen_crate_map;
2497 let sym_name = if is_top {
2498 ~"_rust_crate_map_toplevel"
2500 symname("_rust_crate_map_" + mapmeta.crateid.name,
2501 mapmeta.crate_hash.as_str(),
2502 mapmeta.crateid.version_or_default())
2505 let slicetype = Type::struct_([int_type, int_type], false);
2506 let maptype = Type::struct_([
2507 Type::i32(), // version
2508 slicetype, // child modules
2509 slicetype, // sub crate-maps
2510 int_type.ptr_to(), // event loop factory
2512 let map = sym_name.with_c_str(|buf| {
2514 llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2517 lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2519 // On windows we'd like to export the toplevel cratemap
2520 // such that we can find it from libstd.
2521 if targ_cfg.os == OsWin32 && is_top {
2522 unsafe { llvm::LLVMRustSetDLLExportStorageClass(map) }
2525 return (sym_name, map);
2528 pub fn fill_crate_map(ccx: @CrateContext, map: ValueRef) {
2529 let mut subcrates: ~[ValueRef] = ~[];
2531 let cstore = ccx.sess.cstore;
2532 while cstore.have_crate_data(i) {
2533 let cdata = cstore.get_crate_data(i);
2534 let nm = symname(format!("_rust_crate_map_{}", cdata.name),
2535 cstore.get_crate_hash(i).as_str(),
2536 cstore.get_crate_id(i).version_or_default());
2537 let cr = nm.with_c_str(|buf| {
2539 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2542 subcrates.push(p2i(ccx, cr));
2545 let event_loop_factory = match ccx.tcx.lang_items.event_loop_factory() {
2546 Some(did) => unsafe {
2548 llvm::LLVMConstPointerCast(get_item_val(ccx, did.node),
2549 ccx.int_type.ptr_to().to_ref())
2551 let name = csearch::get_symbol(ccx.sess.cstore, did);
2552 let global = name.with_c_str(|buf| {
2553 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2558 None => C_null(ccx.int_type.ptr_to())
2561 let maptype = Type::array(&ccx.int_type, subcrates.len() as u64);
2562 let vec_elements = "_crate_map_child_vectors".with_c_str(|buf| {
2563 llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2565 lib::llvm::SetLinkage(vec_elements, lib::llvm::InternalLinkage);
2567 llvm::LLVMSetInitializer(vec_elements, C_array(ccx.int_type, subcrates));
2568 let (mod_map, mod_count) = create_module_map(ccx);
2570 llvm::LLVMSetInitializer(map, C_struct(
2574 C_uint(ccx, mod_count)
2577 p2i(ccx, vec_elements),
2578 C_uint(ccx, subcrates.len())
2585 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2586 -> encoder::EncodeParams<'r> {
2588 let diag = cx.sess.diagnostic();
2589 let item_symbols = &cx.item_symbols;
2590 let link_meta = &cx.link_meta;
2591 encoder::EncodeParams {
2594 reexports2: cx.exp_map2,
2595 item_symbols: item_symbols,
2596 non_inlineable_statics: &cx.non_inlineable_statics,
2597 link_meta: link_meta,
2598 cstore: cx.sess.cstore,
2599 encode_inlined_item: ie,
2603 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> ~[u8] {
2606 if !cx.sess.building_library.get() {
2610 let encode_inlined_item: encoder::EncodeInlinedItem =
2611 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii, cx.maps);
2613 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2614 let metadata = encoder::encode_metadata(encode_parms, krate);
2615 let compressed = encoder::metadata_encoding_version +
2616 flate::deflate_bytes(metadata).as_slice();
2617 let llmeta = C_bytes(compressed);
2618 let llconst = C_struct([llmeta], false);
2619 let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2620 cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2621 let llglobal = name.with_c_str(|buf| {
2623 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2627 llvm::LLVMSetInitializer(llglobal, llconst);
2628 cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2629 llvm::LLVMSetSection(llglobal, buf)
2635 pub fn trans_crate(sess: session::Session,
2637 analysis: &CrateAnalysis,
2638 output: &OutputFilenames) -> CrateTranslation {
2639 // Before we touch LLVM, make sure that multithreading is enabled.
2641 use sync::one::{Once, ONCE_INIT};
2642 static mut INIT: Once = ONCE_INIT;
2643 static mut POISONED: bool = false;
2645 if llvm::LLVMStartMultithreaded() != 1 {
2646 // use an extra bool to make sure that all future usage of LLVM
2647 // cannot proceed despite the Once not running more than once.
2653 sess.bug("couldn't enable multi-threaded LLVM");
2657 let link_meta = link::build_link_meta(&krate, output);
2659 // Append ".rs" to crate name as LLVM module identifier.
2661 // LLVM code generator emits a ".file filename" directive
2662 // for ELF backends. Value of the "filename" is set as the
2663 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2664 // crashes if the module identifer is same as other symbols
2665 // such as a function name in the module.
2666 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2667 let llmod_id = link_meta.crateid.name + ".rs";
2669 let ccx = @CrateContext::new(sess,
2676 analysis.reachable);
2678 let _icx = push_ctxt("text");
2679 trans_mod(ccx, &krate.module);
2682 decl_gc_metadata(ccx, llmod_id);
2683 fill_crate_map(ccx, ccx.crate_map);
2685 // win32: wart with exporting crate_map symbol
2686 // We set the crate map (_rust_crate_map_toplevel) to use dll_export
2687 // linkage but that ends up causing the linker to look for a
2688 // __rust_crate_map_toplevel symbol (extra underscore) which it will
2689 // subsequently fail to find. So to mitigate that we just introduce
2690 // an alias from the symbol it expects to the one that actually exists.
2691 if ccx.sess.targ_cfg.os == OsWin32 && !ccx.sess.building_library.get() {
2693 let maptype = val_ty(ccx.crate_map).to_ref();
2695 "__rust_crate_map_toplevel".with_c_str(|buf| {
2697 llvm::LLVMAddAlias(ccx.llmod, maptype,
2698 ccx.crate_map, buf);
2703 glue::emit_tydescs(ccx);
2704 if ccx.sess.opts.debuginfo != NoDebugInfo {
2705 debuginfo::finalize(ccx);
2708 // Translate the metadata.
2709 let metadata = write_metadata(ccx, &krate);
2710 if ccx.sess.trans_stats() {
2711 println!("--- trans stats ---");
2712 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2713 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2714 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2715 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2717 println!("n_fns: {}", ccx.stats.n_fns.get());
2718 println!("n_monos: {}", ccx.stats.n_monos.get());
2719 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2720 println!("n_closures: {}", ccx.stats.n_closures.get());
2721 println!("fn stats:");
2723 let mut fn_stats = ccx.stats.fn_stats.borrow_mut();
2724 fn_stats.get().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2725 insns_b.cmp(&insns_a)
2727 for tuple in fn_stats.get().iter() {
2729 (ref name, ms, insns) => {
2730 println!("{} insns, {} ms, {}", insns, ms, *name);
2736 if ccx.sess.count_llvm_insns() {
2737 let llvm_insns = ccx.stats.llvm_insns.borrow();
2738 for (k, v) in llvm_insns.get().iter() {
2739 println!("{:7u} {}", *v, *k);
2743 let llcx = ccx.llcx;
2744 let link_meta = ccx.link_meta.clone();
2745 let llmod = ccx.llmod;
2747 let mut reachable = {
2748 let reachable_map = ccx.reachable.borrow();
2749 reachable_map.get().iter().filter_map(|id| {
2750 let item_symbols = ccx.item_symbols.borrow();
2751 item_symbols.get().find(id).map(|s| s.to_owned())
2755 // Make sure that some other crucial symbols are not eliminated from the
2756 // module. This includes the main function, the crate map (used for debug
2757 // log settings and I/O), and finally the curious rust_stack_exhausted
2758 // symbol. This symbol is required for use by the libmorestack library that
2759 // we link in, so we must ensure that this symbol is not internalized (if
2760 // defined in the crate).
2761 reachable.push(ccx.crate_map_name.to_owned());
2762 reachable.push(~"main");
2763 reachable.push(~"rust_stack_exhausted");
2764 reachable.push(~"rust_eh_personality"); // referenced from .eh_frame section on some platforms
2765 reachable.push(~"rust_eh_personality_catch"); // referenced from rt/rust_try.ll
2767 return CrateTranslation {
2771 metadata_module: ccx.metadata_llmod,
2773 reachable: reachable,