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, Vector};
37 use metadata::{csearch, encoder};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::build::*;
43 use middle::trans::builder::{Builder, noname};
44 use middle::trans::callee;
45 use middle::trans::cleanup;
46 use middle::trans::cleanup::CleanupMethods;
47 use middle::trans::common::*;
48 use middle::trans::consts;
49 use middle::trans::controlflow;
50 use middle::trans::datum;
51 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
52 use middle::trans::debuginfo;
53 use middle::trans::expr;
54 use middle::trans::foreign;
55 use middle::trans::glue;
56 use middle::trans::inline;
57 use middle::trans::machine;
58 use middle::trans::machine::{llalign_of_min, llsize_of};
59 use middle::trans::meth;
60 use middle::trans::monomorphize;
61 use middle::trans::tvec;
62 use middle::trans::type_::Type;
63 use middle::trans::type_of;
64 use middle::trans::type_of::*;
65 use middle::trans::value::Value;
68 use util::common::indenter;
69 use util::ppaux::{Repr, ty_to_str};
70 use util::sha2::Sha256;
71 use util::nodemap::NodeMap;
73 use arena::TypedArena;
75 use std::c_str::ToCStr;
76 use std::cell::{Cell, RefCell};
79 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
80 use syntax::ast_util::{local_def, is_local};
81 use syntax::attr::AttrMetaMethods;
83 use syntax::codemap::Span;
84 use syntax::parse::token::InternedString;
85 use syntax::visit::Visitor;
87 use syntax::{ast, ast_util, ast_map};
91 local_data_key!(task_local_insn_key: Vec<&'static str> )
93 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
94 local_data::get(task_local_insn_key, |c| {
96 Some(ctx) => blk(ctx.as_slice()),
102 pub fn init_insn_ctxt() {
103 local_data::set(task_local_insn_key, Vec::new());
106 pub struct _InsnCtxt { _x: () }
109 impl Drop for _InsnCtxt {
111 local_data::modify(task_local_insn_key, |c| {
120 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
121 debug!("new InsnCtxt: {}", s);
122 local_data::modify(task_local_insn_key, |c| {
131 pub struct StatRecorder<'a> {
132 ccx: &'a CrateContext,
138 impl<'a> StatRecorder<'a> {
139 pub fn new(ccx: &'a CrateContext, name: ~str) -> StatRecorder<'a> {
140 let start = if ccx.sess().trans_stats() {
141 time::precise_time_ns()
145 let istart = ccx.stats.n_llvm_insns.get();
156 impl<'a> Drop for StatRecorder<'a> {
158 if self.ccx.sess().trans_stats() {
159 let end = time::precise_time_ns();
160 let elapsed = ((end - self.start) / 1_000_000) as uint;
161 let iend = self.ccx.stats.n_llvm_insns.get();
162 self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
164 iend - self.istart));
165 self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
166 // Reset LLVM insn count to avoid compound costs.
167 self.ccx.stats.n_llvm_insns.set(self.istart);
172 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
173 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
174 ty: Type, output: ty::t) -> ValueRef {
175 let llfn: ValueRef = name.with_c_str(|buf| {
177 llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
181 match ty::get(output).sty {
182 // functions returning bottom may unwind, but can never return normally
185 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
188 // `~` pointer return values never alias because ownership is transferred
189 ty::ty_uniq(..) // | ty::ty_trait(_, _, ty::UniqTraitStore, _, _)
192 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
198 lib::llvm::SetFunctionCallConv(llfn, cc);
199 // Function addresses in Rust are never significant, allowing functions to be merged.
200 lib::llvm::SetUnnamedAddr(llfn, true);
201 set_split_stack(llfn);
206 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
207 pub fn decl_cdecl_fn(llmod: ModuleRef,
210 output: ty::t) -> ValueRef {
211 decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
214 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
215 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
216 name: &str, cc: lib::llvm::CallConv,
217 ty: Type, output: ty::t) -> ValueRef {
218 match externs.find_equiv(&name) {
219 Some(n) => return *n,
222 let f = decl_fn(llmod, name, cc, ty, output);
223 externs.insert(name.to_owned(), f);
227 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
228 name: &str, did: ast::DefId) -> ValueRef {
229 match ccx.externs.borrow().find_equiv(&name) {
230 Some(n) => return *n,
234 let f = decl_rust_fn(ccx, false, inputs, output, name);
235 csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
236 set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).collect::<~[_]>(), f)
239 ccx.externs.borrow_mut().insert(name.to_owned(), f);
243 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
244 inputs: &[ty::t], output: ty::t,
245 name: &str) -> ValueRef {
246 use middle::ty::{BrAnon, ReLateBound};
248 let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
249 let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
251 let uses_outptr = type_of::return_uses_outptr(ccx, output);
252 let offset = if uses_outptr { 1 } else { 0 };
253 let offset = if has_env { offset + 1 } else { offset };
255 for (i, &arg_ty) in inputs.iter().enumerate() {
256 let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
257 match ty::get(arg_ty).sty {
258 // `~` pointer parameters never alias because ownership is transferred
261 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
264 // `&mut` pointer parameters never alias other parameters, or mutable global data
265 ty::ty_rptr(_, mt) if mt.mutbl == ast::MutMutable => {
267 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
270 // When a reference in an argument has no named lifetime, it's impossible for that
271 // reference to escape this function (returned or stored beyond the call by a closure).
272 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
273 debug!("marking argument of {} as nocapture because of anonymous lifetime", name);
275 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
279 // For non-immediate arguments the callee gets its own copy of
280 // the value on the stack, so there are no aliases
281 if !type_is_immediate(ccx, arg_ty) {
283 llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
284 llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
291 // The out pointer will never alias with any other pointers, as the object only exists at a
292 // language level after the call. It can also be tagged with SRet to indicate that it is
293 // guaranteed to point to a usable block of memory for the type.
296 let outptr = llvm::LLVMGetParam(llfn, 0);
297 llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
298 llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
305 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
306 inputs: &[ty::t], output: ty::t,
307 name: &str) -> ValueRef {
308 let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
309 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
313 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
314 name: &str, ty: Type) -> ValueRef {
315 match externs.find_equiv(&name) {
316 Some(n) => return *n,
320 let c = name.with_c_str(|buf| {
321 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
323 externs.insert(name.to_owned(), c);
328 // Returns a pointer to the body for the box. The box may be an opaque
329 // box. The result will be casted to the type of body_t, if it is statically
331 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
332 let _icx = push_ctxt("at_box_body");
334 let ty = Type::at_box(ccx, type_of(ccx, body_t));
335 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
336 GEPi(bcx, boxptr, [0u, abi::box_field_body])
339 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
340 match bcx.tcx().lang_items.require(it) {
343 bcx.sess().fatal(format!("allocation of `{}` {}",
344 bcx.ty_to_str(info_ty), s));
349 // The following malloc_raw_dyn* functions allocate a box to contain
350 // a given type, but with a potentially dynamic size.
352 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
356 let _icx = push_ctxt("malloc_raw_exchange");
360 let r = callee::trans_lang_call(bcx,
361 require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
365 let llty_ptr = type_of::type_of(ccx, ptr_ty);
366 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
369 pub fn malloc_raw_dyn_managed<'a>(
375 let _icx = push_ctxt("malloc_raw_managed");
378 let langcall = require_alloc_fn(bcx, t, alloc_fn);
380 // Grab the TypeRef type of box_ptr_ty.
381 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
382 let llty = type_of(ccx, box_ptr_ty);
383 let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
386 let drop_glue = glue::get_drop_glue(ccx, t);
387 let r = callee::trans_lang_call(
391 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
396 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
399 // Type descriptor and type glue stuff
401 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
402 match ccx.tydescs.borrow().find(&t) {
403 Some(inf) => return inf.clone(),
407 ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
408 let inf = Rc::new(glue::declare_tydesc(ccx, t));
410 ccx.tydescs.borrow_mut().insert(t, inf.clone());
414 #[allow(dead_code)] // useful
415 pub fn set_optimize_for_size(f: ValueRef) {
416 lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
419 pub fn set_no_inline(f: ValueRef) {
420 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
423 #[allow(dead_code)] // useful
424 pub fn set_no_unwind(f: ValueRef) {
425 lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
428 // Tell LLVM to emit the information necessary to unwind the stack for the
430 pub fn set_uwtable(f: ValueRef) {
431 lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
434 pub fn set_inline_hint(f: ValueRef) {
435 lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
438 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
440 // Set the inline hint if there is one
441 match find_inline_attr(attrs) {
442 InlineHint => set_inline_hint(llfn),
443 InlineAlways => set_always_inline(llfn),
444 InlineNever => set_no_inline(llfn),
445 InlineNone => { /* fallthrough */ }
448 // Add the no-split-stack attribute if requested
449 if contains_name(attrs, "no_split_stack") {
450 unset_split_stack(llfn);
453 if contains_name(attrs, "cold") {
454 unsafe { llvm::LLVMAddColdAttribute(llfn) }
458 pub fn set_always_inline(f: ValueRef) {
459 lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
462 pub fn set_split_stack(f: ValueRef) {
463 "split-stack".with_c_str(|buf| {
464 unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
468 pub fn unset_split_stack(f: ValueRef) {
469 "split-stack".with_c_str(|buf| {
470 unsafe { llvm::LLVMRemoveFunctionAttrString(f, buf); }
474 // Double-check that we never ask LLVM to declare the same symbol twice. It
475 // silently mangles such symbols, breaking our linkage model.
476 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
477 if ccx.all_llvm_symbols.borrow().contains(&sym) {
478 ccx.sess().bug("duplicate LLVM symbol: ".to_owned() + sym);
480 ccx.all_llvm_symbols.borrow_mut().insert(sym);
484 pub fn get_res_dtor(ccx: &CrateContext,
486 parent_id: ast::DefId,
489 let _icx = push_ctxt("trans_res_dtor");
490 let did = if did.krate != ast::LOCAL_CRATE {
491 inline::maybe_instantiate_inline(ccx, did)
495 if !substs.is_empty() {
496 assert_eq!(did.krate, ast::LOCAL_CRATE);
497 let tsubsts = ty::substs {
498 regions: ty::ErasedRegions,
500 tps: Vec::from_slice(substs),
503 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, &tsubsts);
504 let (val, _) = monomorphize::monomorphic_fn(ccx, did, &tsubsts, vtables, None, None);
507 } else if did.krate == ast::LOCAL_CRATE {
508 get_item_val(ccx, did.node)
511 let name = csearch::get_symbol(&ccx.sess().cstore, did);
512 let class_ty = ty::subst_tps(tcx,
515 ty::lookup_item_type(tcx, parent_id).ty);
516 let llty = type_of_dtor(ccx, class_ty);
518 get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
519 lib::llvm::CCallConv, llty, ty::mk_nil())
523 // Structural comparison: a rather involved form of glue.
524 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
525 if cx.sess().opts.cg.save_temps {
528 llvm::LLVMSetValueName(v, buf)
535 // Used only for creating scalar comparison glue.
536 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
538 // NB: This produces an i1, not a Rust bool (i8).
539 pub fn compare_scalar_types<'a>(
546 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
548 match ty::get(t).sty {
549 ty::ty_nil => f(nil_type),
550 ty::ty_bool | ty::ty_ptr(_) |
551 ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
552 ty::ty_int(_) => f(signed_int),
553 ty::ty_float(_) => f(floating_point),
554 // Should never get here, because t is scalar.
555 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
560 // A helper function to do the actual comparison of scalar values.
561 pub fn compare_scalar_values<'a>(
568 let _icx = push_ctxt("compare_scalar_values");
569 fn die(cx: &Block) -> ! {
570 cx.sess().bug("compare_scalar_values: must be a comparison operator");
574 // We don't need to do actual comparisons for nil.
575 // () == () holds but () < () does not.
577 ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(cx.ccx(), true),
578 ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(cx.ccx(), false),
579 // refinements would be nice
585 ast::BiEq => lib::llvm::RealOEQ,
586 ast::BiNe => lib::llvm::RealUNE,
587 ast::BiLt => lib::llvm::RealOLT,
588 ast::BiLe => lib::llvm::RealOLE,
589 ast::BiGt => lib::llvm::RealOGT,
590 ast::BiGe => lib::llvm::RealOGE,
593 return FCmp(cx, cmp, lhs, rhs);
597 ast::BiEq => lib::llvm::IntEQ,
598 ast::BiNe => lib::llvm::IntNE,
599 ast::BiLt => lib::llvm::IntSLT,
600 ast::BiLe => lib::llvm::IntSLE,
601 ast::BiGt => lib::llvm::IntSGT,
602 ast::BiGe => lib::llvm::IntSGE,
605 return ICmp(cx, cmp, lhs, rhs);
609 ast::BiEq => lib::llvm::IntEQ,
610 ast::BiNe => lib::llvm::IntNE,
611 ast::BiLt => lib::llvm::IntULT,
612 ast::BiLe => lib::llvm::IntULE,
613 ast::BiGt => lib::llvm::IntUGT,
614 ast::BiGe => lib::llvm::IntUGE,
617 return ICmp(cx, cmp, lhs, rhs);
622 pub fn compare_simd_types(
630 match ty::get(t).sty {
632 // The comparison operators for floating point vectors are challenging.
633 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
634 // then bitcast to a floating point vector, the result will be `-NaN`
635 // for each truth value. Because of this they are unsupported.
636 cx.sess().bug("compare_simd_types: comparison operators \
637 not supported for floating point SIMD types")
639 ty::ty_uint(_) | ty::ty_int(_) => {
641 ast::BiEq => lib::llvm::IntEQ,
642 ast::BiNe => lib::llvm::IntNE,
643 ast::BiLt => lib::llvm::IntSLT,
644 ast::BiLe => lib::llvm::IntSLE,
645 ast::BiGt => lib::llvm::IntSGT,
646 ast::BiGe => lib::llvm::IntSGE,
647 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
649 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
650 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
651 // to get the correctly sized type. This will compile to a single instruction
652 // once the IR is converted to assembly if the SIMD instruction is supported
653 // by the target architecture.
654 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
656 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
660 pub type val_and_ty_fn<'r,'b> =
661 |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
663 // Iterates through the elements of a structural type.
664 pub fn iter_structural_ty<'r,
669 f: val_and_ty_fn<'r,'b>)
671 let _icx = push_ctxt("iter_structural_ty");
678 variant: &ty::VariantInfo,
680 f: val_and_ty_fn<'r,'b>)
682 let _icx = push_ctxt("iter_variant");
686 for (i, &arg) in variant.args.iter().enumerate() {
688 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
689 ty::subst_tps(tcx, tps, None, arg));
695 match ty::get(t).sty {
696 ty::ty_struct(..) => {
697 let repr = adt::represent_type(cx.ccx(), t);
698 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
699 for (i, field_ty) in field_tys.iter().enumerate() {
700 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
701 cx = f(cx, llfld_a, field_ty.mt.ty);
705 ty::ty_vec(_, Some(n)) => {
706 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
707 let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
708 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
710 ty::ty_tup(ref args) => {
711 let repr = adt::represent_type(cx.ccx(), t);
712 for (i, arg) in args.iter().enumerate() {
713 let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
714 cx = f(cx, llfld_a, *arg);
717 ty::ty_enum(tid, ref substs) => {
721 let repr = adt::represent_type(ccx, t);
722 let variants = ty::enum_variants(ccx.tcx(), tid);
723 let n_variants = (*variants).len();
725 // NB: we must hit the discriminant first so that structural
726 // comparison know not to proceed when the discriminants differ.
728 match adt::trans_switch(cx, &*repr, av) {
729 (_match::single, None) => {
730 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
731 substs.tps.as_slice(), f);
733 (_match::switch, Some(lldiscrim_a)) => {
734 cx = f(cx, lldiscrim_a, ty::mk_int());
735 let unr_cx = fcx.new_temp_block("enum-iter-unr");
737 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
739 let next_cx = fcx.new_temp_block("enum-iter-next");
741 for variant in (*variants).iter() {
743 fcx.new_temp_block("enum-iter-variant-".to_owned() +
744 variant.disr_val.to_str());
745 match adt::trans_case(cx, &*repr, variant.disr_val) {
746 _match::single_result(r) => {
747 AddCase(llswitch, r.val, variant_cx.llbb)
749 _ => ccx.sess().unimpl("value from adt::trans_case \
750 in iter_structural_ty")
753 iter_variant(variant_cx,
757 substs.tps.as_slice(),
759 Br(variant_cx, next_cx.llbb);
763 _ => ccx.sess().unimpl("value from adt::trans_switch \
764 in iter_structural_ty")
767 _ => cx.sess().unimpl("type in iter_structural_ty")
772 pub fn cast_shift_expr_rhs<'a>(
778 cast_shift_rhs(op, lhs, rhs,
779 |a,b| Trunc(cx, a, b),
780 |a,b| ZExt(cx, a, b))
783 pub fn cast_shift_const_rhs(op: ast::BinOp,
784 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
785 cast_shift_rhs(op, lhs, rhs,
786 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
787 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
790 pub fn cast_shift_rhs(op: ast::BinOp,
793 trunc: |ValueRef, Type| -> ValueRef,
794 zext: |ValueRef, Type| -> ValueRef)
796 // Shifts may have any size int on the rhs
798 if ast_util::is_shift_binop(op) {
799 let mut rhs_llty = val_ty(rhs);
800 let mut lhs_llty = val_ty(lhs);
801 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
802 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
803 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
804 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
807 } else if lhs_sz > rhs_sz {
808 // FIXME (#1877: If shifting by negative
809 // values becomes not undefined then this is wrong.
820 pub fn fail_if_zero<'a>(
827 let text = if divrem == ast::BiDiv {
828 "attempted to divide by zero"
830 "attempted remainder with a divisor of zero"
832 let is_zero = match ty::get(rhs_t).sty {
834 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
835 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
838 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
839 ICmp(cx, lib::llvm::IntEQ, rhs, zero)
842 cx.sess().bug("fail-if-zero on unexpected type: ".to_owned() +
843 ty_to_str(cx.tcx(), rhs_t));
846 with_cond(cx, is_zero, |bcx| {
847 controlflow::trans_fail(bcx, span, InternedString::new(text))
851 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
852 let name = csearch::get_symbol(&ccx.sess().cstore, did);
853 match ty::get(t).sty {
854 ty::ty_bare_fn(ref fn_ty) => {
855 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
856 ccx.sess().targ_cfg.arch) {
857 Some(Rust) | Some(RustIntrinsic) => {
858 get_extern_rust_fn(ccx,
859 fn_ty.sig.inputs.as_slice(),
865 let c = foreign::llvm_calling_convention(ccx, fn_ty.abi);
866 let cconv = c.unwrap_or(lib::llvm::CCallConv);
867 let llty = type_of_fn_from_ty(ccx, t);
868 get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod,
869 name, cconv, llty, fn_ty.sig.output)
873 ty::ty_closure(ref f) => {
874 get_extern_rust_fn(ccx,
875 f.sig.inputs.as_slice(),
881 let llty = type_of(ccx, t);
882 get_extern_const(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
891 llargs: Vec<ValueRef> ,
892 attributes: &[(uint, lib::llvm::Attribute)],
893 call_info: Option<NodeInfo>)
894 -> (ValueRef, &'a Block<'a>) {
895 let _icx = push_ctxt("invoke_");
896 if bcx.unreachable.get() {
897 return (C_null(Type::i8(bcx.ccx())), bcx);
900 match bcx.opt_node_id {
902 debug!("invoke at ???");
905 debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
909 if need_invoke(bcx) {
910 debug!("invoking {} at {}", llfn, bcx.llbb);
911 for &llarg in llargs.iter() {
912 debug!("arg: {}", llarg);
914 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
915 let landing_pad = bcx.fcx.get_landing_pad();
918 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
919 None => debuginfo::clear_source_location(bcx.fcx)
922 let llresult = Invoke(bcx,
928 return (llresult, normal_bcx);
930 debug!("calling {} at {}", llfn, bcx.llbb);
931 for &llarg in llargs.iter() {
932 debug!("arg: {}", llarg);
936 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
937 None => debuginfo::clear_source_location(bcx.fcx)
940 let llresult = Call(bcx, llfn, llargs.as_slice(), attributes);
941 return (llresult, bcx);
945 pub fn need_invoke(bcx: &Block) -> bool {
946 if bcx.sess().no_landing_pads() {
950 // Avoid using invoke if we are already inside a landing pad.
955 bcx.fcx.needs_invoke()
958 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
959 let _icx = push_ctxt("load_if_immediate");
960 if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
964 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
965 match local.pat.node {
966 ast::PatWild => true, _ => false
970 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
973 debug!("init_local(bcx={}, local.id={:?})",
974 bcx.to_str(), local.id);
975 let _indenter = indenter();
977 let _icx = push_ctxt("init_local");
979 if ignore_lhs(bcx, local) {
980 // Handle let _ = e; just like e;
983 return controlflow::trans_stmt_semi(bcx, init)
985 None => { return bcx; }
989 _match::store_local(bcx, local)
992 pub fn raw_block<'a>(
993 fcx: &'a FunctionContext<'a>,
997 Block::new(llbb, is_lpad, None, fcx)
1000 pub fn with_cond<'a>(
1003 f: |&'a Block<'a>| -> &'a Block<'a>)
1005 let _icx = push_ctxt("with_cond");
1007 let next_cx = fcx.new_temp_block("next");
1008 let cond_cx = fcx.new_temp_block("cond");
1009 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1010 let after_cx = f(cond_cx);
1011 if !after_cx.terminated.get() {
1012 Br(after_cx, next_cx.llbb);
1017 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1018 let _icx = push_ctxt("call_memcpy");
1020 let key = match ccx.sess().targ_cfg.arch {
1021 X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1022 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1024 let memcpy = ccx.get_intrinsic(&key);
1025 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1026 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1027 let size = IntCast(cx, n_bytes, ccx.int_type);
1028 let align = C_i32(ccx, align as i32);
1029 let volatile = C_i1(ccx, false);
1030 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1033 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1034 let _icx = push_ctxt("memcpy_ty");
1035 let ccx = bcx.ccx();
1036 if ty::type_is_structural(t) {
1037 let llty = type_of::type_of(ccx, t);
1038 let llsz = llsize_of(ccx, llty);
1039 let llalign = llalign_of_min(ccx, llty);
1040 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1042 Store(bcx, Load(bcx, src), dst);
1046 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1047 if cx.unreachable.get() { return; }
1048 let _icx = push_ctxt("zero_mem");
1051 let llty = type_of::type_of(ccx, t);
1052 memzero(&B(bcx), llptr, llty);
1055 // Always use this function instead of storing a zero constant to the memory
1056 // in question. If you store a zero constant, LLVM will drown in vreg
1057 // allocation for large data structures, and the generated code will be
1058 // awful. (A telltale sign of this is large quantities of
1059 // `mov [byte ptr foo],0` in the generated code.)
1060 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1061 let _icx = push_ctxt("memzero");
1064 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1065 X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1066 X86_64 => "llvm.memset.p0i8.i64"
1069 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1070 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1071 let llzeroval = C_u8(ccx, 0);
1072 let size = machine::llsize_of(ccx, ty);
1073 let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1074 let volatile = C_i1(ccx, false);
1075 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1078 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1079 let _icx = push_ctxt("alloc_ty");
1080 let ccx = bcx.ccx();
1081 let ty = type_of::type_of(ccx, t);
1082 assert!(!ty::type_has_params(t));
1083 let val = alloca(bcx, ty, name);
1087 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1088 alloca_maybe_zeroed(cx, ty, name, false)
1091 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1092 let _icx = push_ctxt("alloca");
1093 if cx.unreachable.get() {
1095 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1098 debuginfo::clear_source_location(cx.fcx);
1099 let p = Alloca(cx, ty, name);
1101 let b = cx.fcx.ccx.builder();
1102 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1108 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1109 let _icx = push_ctxt("arrayalloca");
1110 if cx.unreachable.get() {
1112 return llvm::LLVMGetUndef(ty.to_ref());
1115 debuginfo::clear_source_location(cx.fcx);
1116 return ArrayAlloca(cx, ty, v);
1119 // Creates and returns space for, or returns the argument representing, the
1120 // slot where the return value of the function must go.
1121 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1124 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1125 llvm::LLVMGetParam(fcx.llfn, 0)
1127 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1128 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1129 Alloca(bcx, lloutputtype, "__make_return_pointer")
1134 // NB: must keep 4 fns in sync:
1137 // - create_datums_for_fn_args.
1141 // Be warned! You must call `init_function` before doing anything with the
1142 // returned function context.
1143 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1148 param_substs: Option<&'a param_substs>,
1150 block_arena: &'a TypedArena<Block<'a>>)
1151 -> FunctionContext<'a> {
1152 for p in param_substs.iter() { p.validate(); }
1154 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1155 if id == -1 { "".to_owned() } else { ccx.tcx.map.path_to_str(id) },
1156 id, param_substs.map(|s| s.repr(ccx.tcx())));
1158 let substd_output_type = match param_substs {
1159 None => output_type,
1161 ty::subst_tps(ccx.tcx(),
1162 substs.tys.as_slice(),
1167 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1168 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1170 let mut fcx = FunctionContext {
1173 llretptr: Cell::new(None),
1174 entry_bcx: RefCell::new(None),
1175 alloca_insert_pt: Cell::new(None),
1176 llreturn: Cell::new(None),
1177 personality: Cell::new(None),
1178 caller_expects_out_pointer: uses_outptr,
1179 llargs: RefCell::new(NodeMap::new()),
1180 lllocals: RefCell::new(NodeMap::new()),
1181 llupvars: RefCell::new(NodeMap::new()),
1183 param_substs: param_substs,
1185 block_arena: block_arena,
1187 debug_context: debug_context,
1188 scopes: RefCell::new(Vec::new())
1192 fcx.llenv = Some(unsafe {
1193 llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1200 /// Performs setup on a newly created function, creating the entry scope block
1201 /// and allocating space for the return pointer.
1202 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1204 output_type: ty::t) {
1205 let entry_bcx = fcx.new_temp_block("entry-block");
1207 *fcx.entry_bcx.borrow_mut() = Some(entry_bcx);
1209 // Use a dummy instruction as the insertion point for all allocas.
1210 // This is later removed in FunctionContext::cleanup.
1211 fcx.alloca_insert_pt.set(Some(unsafe {
1212 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1213 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1216 // This shouldn't need to recompute the return type,
1217 // as new_fn_ctxt did it already.
1218 let substd_output_type = match fcx.param_substs {
1219 None => output_type,
1221 ty::subst_tps(fcx.ccx.tcx(),
1222 substs.tys.as_slice(),
1228 if !return_type_is_void(fcx.ccx, substd_output_type) {
1229 // If the function returns nil/bot, there is no real return
1230 // value, so do not set `llretptr`.
1231 if !skip_retptr || fcx.caller_expects_out_pointer {
1232 // Otherwise, we normally allocate the llretptr, unless we
1233 // have been instructed to skip it for immediate return
1235 fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1240 // NB: must keep 4 fns in sync:
1243 // - create_datums_for_fn_args.
1247 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1248 use middle::trans::datum::{ByRef, ByValue};
1251 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1255 // work around bizarre resolve errors
1256 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1257 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1259 // create_datums_for_fn_args: creates rvalue datums for each of the
1260 // incoming function arguments. These will later be stored into
1261 // appropriate lvalue datums.
1262 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1264 -> Vec<RvalueDatum> {
1265 let _icx = push_ctxt("create_datums_for_fn_args");
1267 // Return an array wrapping the ValueRefs that we get from
1268 // llvm::LLVMGetParam for each argument into datums.
1269 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1270 let llarg = unsafe {
1271 llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1273 datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1277 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1278 arg_scope: cleanup::CustomScopeIndex,
1281 arg_datums: Vec<RvalueDatum> )
1283 debug!("copy_args_to_allocas");
1285 let _icx = push_ctxt("copy_args_to_allocas");
1288 let arg_scope_id = cleanup::CustomScope(arg_scope);
1290 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1291 // For certain mode/type combinations, the raw llarg values are passed
1292 // by value. However, within the fn body itself, we want to always
1293 // have all locals and arguments be by-ref so that we can cancel the
1294 // cleanup and for better interaction with LLVM's debug info. So, if
1295 // the argument would be passed by value, we store it into an alloca.
1296 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1297 // the event it's not truly needed.
1299 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1301 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1302 debuginfo::create_argument_metadata(bcx, &args[i]);
1309 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1310 // and builds the return block.
1311 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1312 last_bcx: &'a Block<'a>) {
1313 let _icx = push_ctxt("finish_fn");
1315 let ret_cx = match fcx.llreturn.get() {
1317 if !last_bcx.terminated.get() {
1318 Br(last_bcx, llreturn);
1320 raw_block(fcx, false, llreturn)
1324 build_return_block(fcx, ret_cx);
1325 debuginfo::clear_source_location(fcx);
1329 // Builds the return block for a function.
1330 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1331 // Return the value if this function immediate; otherwise, return void.
1332 if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1333 return RetVoid(ret_cx);
1336 let retptr = Value(fcx.llretptr.get().unwrap());
1337 let retval = match retptr.get_dominating_store(ret_cx) {
1338 // If there's only a single store to the ret slot, we can directly return
1339 // the value that was stored and omit the store and the alloca
1341 let retval = s.get_operand(0).unwrap().get();
1342 s.erase_from_parent();
1344 if retptr.has_no_uses() {
1345 retptr.erase_from_parent();
1350 // Otherwise, load the return value from the ret slot
1351 None => Load(ret_cx, fcx.llretptr.get().unwrap())
1355 Ret(ret_cx, retval);
1358 // trans_closure: Builds an LLVM function out of a source function.
1359 // If the function closes over its environment a closure will be
1361 pub fn trans_closure(ccx: &CrateContext,
1365 param_substs: Option<¶m_substs>,
1367 _attributes: &[ast::Attribute],
1369 maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1370 ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1372 let _icx = push_ctxt("trans_closure");
1373 set_uwtable(llfndecl);
1375 debug!("trans_closure(..., param_substs={})",
1376 param_substs.map(|s| s.repr(ccx.tcx())));
1378 let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1379 ty::ty_closure(_) => true,
1383 let arena = TypedArena::new();
1384 let fcx = new_fn_ctxt(ccx,
1389 param_substs.map(|s| &*s),
1392 init_function(&fcx, false, output_type);
1394 // cleanup scope for the incoming arguments
1395 let arg_scope = fcx.push_custom_cleanup_scope();
1397 // Create the first basic block in the function and keep a handle on it to
1398 // pass to finish_fn later.
1399 let bcx_top = fcx.entry_bcx.borrow().clone().unwrap();
1400 let mut bcx = bcx_top;
1401 let block_ty = node_id_type(bcx, body.id);
1403 // Set up arguments to the function.
1404 let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1405 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1407 bcx = copy_args_to_allocas(&fcx,
1410 decl.inputs.as_slice(),
1413 bcx = maybe_load_env(bcx);
1415 // Up until here, IR instructions for this function have explicitly not been annotated with
1416 // source code location, so we don't step into call setup code. From here on, source location
1417 // emitting should be enabled.
1418 debuginfo::start_emitting_source_locations(&fcx);
1420 let dest = match fcx.llretptr.get() {
1421 Some(e) => {expr::SaveIn(e)}
1423 assert!(type_is_zero_size(bcx.ccx(), block_ty))
1428 // This call to trans_block is the place where we bridge between
1429 // translation calls that don't have a return value (trans_crate,
1430 // trans_mod, trans_item, et cetera) and those that do
1431 // (trans_block, trans_expr, et cetera).
1432 bcx = controlflow::trans_block(bcx, body, dest);
1434 match fcx.llreturn.get() {
1436 Br(bcx, fcx.return_exit_block());
1437 fcx.pop_custom_cleanup_scope(arg_scope);
1440 // Microoptimization writ large: avoid creating a separate
1441 // llreturn basic block
1442 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1446 // Put return block after all other blocks.
1447 // This somewhat improves single-stepping experience in debugger.
1449 let llreturn = fcx.llreturn.get();
1450 for &llreturn in llreturn.iter() {
1451 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1455 // Insert the mandatory first few basic blocks before lltop.
1456 finish_fn(&fcx, bcx);
1459 // trans_fn: creates an LLVM function corresponding to a source language
1461 pub fn trans_fn(ccx: &CrateContext,
1465 param_substs: Option<¶m_substs>,
1467 attrs: &[ast::Attribute]) {
1468 let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id));
1469 debug!("trans_fn(param_substs={})", param_substs.map(|s| s.repr(ccx.tcx())));
1470 let _icx = push_ctxt("trans_fn");
1471 let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1472 trans_closure(ccx, decl, body, llfndecl,
1473 param_substs, id, attrs, output_type, |bcx| bcx);
1476 pub fn trans_enum_variant(ccx: &CrateContext,
1477 _enum_id: ast::NodeId,
1478 variant: &ast::Variant,
1479 _args: &[ast::VariantArg],
1481 param_substs: Option<¶m_substs>,
1482 llfndecl: ValueRef) {
1483 let _icx = push_ctxt("trans_enum_variant");
1485 trans_enum_variant_or_tuple_like_struct(
1493 pub fn trans_tuple_struct(ccx: &CrateContext,
1494 _fields: &[ast::StructField],
1495 ctor_id: ast::NodeId,
1496 param_substs: Option<¶m_substs>,
1497 llfndecl: ValueRef) {
1498 let _icx = push_ctxt("trans_tuple_struct");
1500 trans_enum_variant_or_tuple_like_struct(
1508 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1509 ctor_id: ast::NodeId,
1511 param_substs: Option<¶m_substs>,
1512 llfndecl: ValueRef) {
1514 let no_substs: &[ty::t] = [];
1515 let ty_param_substs: &[ty::t] = match param_substs {
1516 Some(substs) => substs.tys.as_slice(),
1520 ty::subst_tps(ccx.tcx(),
1523 ty::node_id_to_type(ccx.tcx(), ctor_id))
1526 let result_ty = match ty::get(ctor_ty).sty {
1527 ty::ty_bare_fn(ref bft) => bft.sig.output,
1528 _ => ccx.sess().bug(
1529 format!("trans_enum_variant_or_tuple_like_struct: \
1530 unexpected ctor return type {}",
1531 ty_to_str(ccx.tcx(), ctor_ty)))
1534 let arena = TypedArena::new();
1535 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1536 param_substs.map(|s| &*s), None, &arena);
1537 init_function(&fcx, false, result_ty);
1539 let arg_tys = ty::ty_fn_args(ctor_ty);
1541 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1543 let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1545 if !type_is_zero_size(fcx.ccx, result_ty) {
1546 let repr = adt::represent_type(ccx, result_ty);
1547 adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1548 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1549 let lldestptr = adt::trans_field_ptr(bcx,
1551 fcx.llretptr.get().unwrap(),
1554 arg_datum.store_to(bcx, lldestptr);
1558 finish_fn(&fcx, bcx);
1561 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1562 id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1564 for &variant in enum_definition.variants.iter() {
1565 let disr_val = vi[*i].disr_val;
1568 match variant.node.kind {
1569 ast::TupleVariantKind(ref args) if args.len() > 0 => {
1570 let llfn = get_item_val(ccx, variant.node.id);
1571 trans_enum_variant(ccx, id, variant, args.as_slice(),
1572 disr_val, None, llfn);
1574 ast::TupleVariantKind(_) => {
1577 ast::StructVariantKind(struct_def) => {
1578 trans_struct_def(ccx, struct_def);
1584 pub struct TransItemVisitor<'a> {
1585 pub ccx: &'a CrateContext,
1588 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1589 fn visit_item(&mut self, i: &ast::Item, _:()) {
1590 trans_item(self.ccx, i);
1594 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1595 let _icx = push_ctxt("trans_item");
1597 ast::ItemFn(decl, fn_style, _abi, ref generics, body) => {
1598 if fn_style == ast::ExternFn {
1599 let llfndecl = get_item_val(ccx, item.id);
1600 foreign::trans_rust_fn_with_foreign_abi(
1601 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1602 } else if !generics.is_type_parameterized() {
1603 let llfn = get_item_val(ccx, item.id);
1610 item.attrs.as_slice());
1612 // Be sure to travel more than just one layer deep to catch nested
1613 // items in blocks and such.
1614 let mut v = TransItemVisitor{ ccx: ccx };
1615 v.visit_block(body, ());
1618 ast::ItemImpl(ref generics, _, _, ref ms) => {
1619 meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1621 ast::ItemMod(ref m) => {
1624 ast::ItemEnum(ref enum_definition, ref generics) => {
1625 if !generics.is_type_parameterized() {
1626 let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1628 trans_enum_def(ccx, enum_definition, item.id, vi.as_slice(), &mut i);
1631 ast::ItemStatic(_, m, expr) => {
1632 consts::trans_const(ccx, m, item.id);
1633 // Do static_assert checking. It can't really be done much earlier
1634 // because we need to get the value of the bool out of LLVM
1635 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1636 if m == ast::MutMutable {
1637 ccx.sess().span_fatal(expr.span,
1638 "cannot have static_assert on a mutable \
1642 let v = ccx.const_values.borrow().get_copy(&item.id);
1644 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1645 ccx.sess().span_fatal(expr.span, "static assertion failed");
1650 ast::ItemForeignMod(ref foreign_mod) => {
1651 foreign::trans_foreign_mod(ccx, foreign_mod);
1653 ast::ItemStruct(struct_def, ref generics) => {
1654 if !generics.is_type_parameterized() {
1655 trans_struct_def(ccx, struct_def);
1658 ast::ItemTrait(..) => {
1659 // Inside of this trait definition, we won't be actually translating any
1660 // functions, but the trait still needs to be walked. Otherwise default
1661 // methods with items will not get translated and will cause ICE's when
1662 // metadata time comes around.
1663 let mut v = TransItemVisitor{ ccx: ccx };
1664 visit::walk_item(&mut v, item, ());
1666 _ => {/* fall through */ }
1670 pub fn trans_struct_def(ccx: &CrateContext, struct_def: @ast::StructDef) {
1671 // If this is a tuple-like struct, translate the constructor.
1672 match struct_def.ctor_id {
1673 // We only need to translate a constructor if there are fields;
1674 // otherwise this is a unit-like struct.
1675 Some(ctor_id) if struct_def.fields.len() > 0 => {
1676 let llfndecl = get_item_val(ccx, ctor_id);
1677 trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1678 ctor_id, None, llfndecl);
1680 Some(_) | None => {}
1684 // Translate a module. Doing this amounts to translating the items in the
1685 // module; there ends up being no artifact (aside from linkage names) of
1686 // separate modules in the compiled program. That's because modules exist
1687 // only as a convenience for humans working with the code, to organize names
1688 // and control visibility.
1689 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1690 let _icx = push_ctxt("trans_mod");
1691 for item in m.items.iter() {
1692 trans_item(ccx, *item);
1696 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1698 ccx.item_symbols.borrow_mut().insert(node_id, sym);
1700 if !ccx.reachable.contains(&node_id) {
1701 lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1704 if is_entry_fn(ccx.sess(), node_id) && !ccx.sess().building_library.get() {
1705 create_entry_wrapper(ccx, sp, llfn);
1709 fn register_fn(ccx: &CrateContext,
1712 node_id: ast::NodeId,
1715 let f = match ty::get(node_type).sty {
1716 ty::ty_bare_fn(ref f) => {
1717 assert!(f.abi == Rust || f.abi == RustIntrinsic);
1720 _ => fail!("expected bare rust fn or an intrinsic")
1723 let llfn = decl_rust_fn(ccx,
1725 f.sig.inputs.as_slice(),
1728 finish_register_fn(ccx, sp, sym, node_id, llfn);
1732 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1733 pub fn register_fn_llvmty(ccx: &CrateContext,
1736 node_id: ast::NodeId,
1737 cc: lib::llvm::CallConv,
1739 output: ty::t) -> ValueRef {
1740 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1742 let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1743 finish_register_fn(ccx, sp, sym, node_id, llfn);
1747 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1748 match *sess.entry_fn.borrow() {
1749 Some((entry_id, _)) => node_id == entry_id,
1754 // Create a _rust_main(args: ~[str]) function which will be called from the
1755 // runtime rust_start function
1756 pub fn create_entry_wrapper(ccx: &CrateContext,
1758 main_llfn: ValueRef) {
1759 let et = ccx.sess().entry_type.get().unwrap();
1761 session::EntryMain => {
1762 create_entry_fn(ccx, main_llfn, true);
1764 session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1765 session::EntryNone => {} // Do nothing.
1768 fn create_entry_fn(ccx: &CrateContext,
1769 rust_main: ValueRef,
1770 use_start_lang_item: bool) {
1771 let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1774 let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1775 let llbb = "top".with_c_str(|buf| {
1777 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1780 let bld = ccx.builder.b;
1782 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1784 let (start_fn, args) = if use_start_lang_item {
1785 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1787 Err(s) => { ccx.sess().fatal(s); }
1789 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1790 get_item_val(ccx, start_def_id.node)
1792 let start_fn_type = csearch::get_type(ccx.tcx(),
1794 trans_external_path(ccx, start_def_id, start_fn_type)
1798 let opaque_rust_main = "rust_main".with_c_str(|buf| {
1799 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1804 llvm::LLVMGetParam(llfn, 0),
1805 llvm::LLVMGetParam(llfn, 1)
1810 debug!("using user-defined start fn");
1812 llvm::LLVMGetParam(llfn, 0 as c_uint),
1813 llvm::LLVMGetParam(llfn, 1 as c_uint)
1819 let result = llvm::LLVMBuildCall(bld,
1822 args.len() as c_uint,
1825 llvm::LLVMBuildRet(bld, result);
1830 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1831 ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1832 match attr::first_attr_value_str_by_name(attrs, "export_name") {
1833 // Use provided name
1834 Some(name) => name.get().to_owned(),
1836 _ => ccx.tcx.map.with_path(id, |mut path| {
1837 if attr::contains_name(attrs, "no_mangle") {
1839 path.last().unwrap().to_str()
1841 // Usual name mangling
1842 mangle_exported_name(ccx, path, ty, id)
1848 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1849 debug!("get_item_val(id=`{:?}`)", id);
1851 match ccx.item_vals.borrow().find_copy(&id) {
1852 Some(v) => return v,
1856 let mut foreign = false;
1857 let item = ccx.tcx.map.get(id);
1858 let val = match item {
1859 ast_map::NodeItem(i) => {
1860 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1861 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1863 let v = match i.node {
1864 ast::ItemStatic(_, _, expr) => {
1865 // If this static came from an external crate, then
1866 // we need to get the symbol from csearch instead of
1867 // using the current crate's name/version
1868 // information in the hash of the symbol
1869 debug!("making {}", sym);
1870 let (sym, is_local) = {
1871 match ccx.external_srcs.borrow().find(&i.id) {
1873 debug!("but found in other crate...");
1874 (csearch::get_symbol(&ccx.sess().cstore,
1881 // We need the translated value here, because for enums the
1882 // LLVM type is not fully determined by the Rust type.
1883 let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1884 ccx.const_values.borrow_mut().insert(id, v);
1885 let mut inlineable = inlineable;
1888 let llty = llvm::LLVMTypeOf(v);
1889 let g = sym.with_c_str(|buf| {
1890 llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1893 if !ccx.reachable.contains(&id) {
1894 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
1897 // Apply the `unnamed_addr` attribute if
1899 if attr::contains_name(i.attrs.as_slice(),
1900 "address_insignificant") {
1901 if ccx.reachable.contains(&id) {
1902 ccx.sess().span_bug(i.span,
1903 "insignificant static is reachable");
1905 lib::llvm::SetUnnamedAddr(g, true);
1907 // This is a curious case where we must make
1908 // all of these statics inlineable. If a
1909 // global is tagged as
1910 // address_insignificant, then LLVM won't
1911 // coalesce globals unless they have an
1912 // internal linkage type. This means that
1913 // external crates cannot use this global.
1914 // This is a problem for things like inner
1915 // statics in generic functions, because the
1916 // function will be inlined into another
1917 // crate and then attempt to link to the
1918 // static in the original crate, only to
1919 // find that it's not there. On the other
1920 // side of inlininig, the crates knows to
1921 // not declare this static as
1922 // available_externally (because it isn't)
1926 if attr::contains_name(i.attrs.as_slice(),
1928 lib::llvm::set_thread_local(g, true);
1932 debug!("{} not inlined", sym);
1933 ccx.non_inlineable_statics.borrow_mut()
1937 ccx.item_symbols.borrow_mut().insert(i.id, sym);
1942 ast::ItemFn(_, fn_style, _, _, _) => {
1943 let llfn = if fn_style != ast::ExternFn {
1944 register_fn(ccx, i.span, sym, i.id, ty)
1946 foreign::register_rust_fn_with_foreign_abi(ccx,
1951 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
1955 _ => fail!("get_item_val: weird result in table")
1958 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
1960 Some(sect) => unsafe {
1961 sect.get().with_c_str(|buf| {
1962 llvm::LLVMSetSection(v, buf);
1971 ast_map::NodeTraitMethod(trait_method) => {
1972 debug!("get_item_val(): processing a NodeTraitMethod");
1973 match *trait_method {
1974 ast::Required(_) => {
1975 ccx.sess().bug("unexpected variant: required trait method in \
1978 ast::Provided(m) => {
1979 register_method(ccx, id, m)
1984 ast_map::NodeMethod(m) => {
1985 register_method(ccx, id, m)
1988 ast_map::NodeForeignItem(ni) => {
1992 ast::ForeignItemFn(..) => {
1993 let abi = ccx.tcx.map.get_foreign_abi(id);
1994 foreign::register_foreign_item_fn(ccx, abi, ni)
1996 ast::ForeignItemStatic(..) => {
1997 foreign::register_static(ccx, ni)
2002 ast_map::NodeVariant(ref v) => {
2004 let args = match v.node.kind {
2005 ast::TupleVariantKind(ref args) => args,
2006 ast::StructVariantKind(_) => {
2007 fail!("struct variant kind unexpected in get_item_val")
2010 assert!(args.len() != 0u);
2011 let ty = ty::node_id_to_type(ccx.tcx(), id);
2012 let parent = ccx.tcx.map.get_parent(id);
2013 let enm = ccx.tcx.map.expect_item(parent);
2014 let sym = exported_name(ccx,
2017 enm.attrs.as_slice());
2019 llfn = match enm.node {
2020 ast::ItemEnum(_, _) => {
2021 register_fn(ccx, (*v).span, sym, id, ty)
2023 _ => fail!("NodeVariant, shouldn't happen")
2025 set_inline_hint(llfn);
2029 ast_map::NodeStructCtor(struct_def) => {
2030 // Only register the constructor if this is a tuple-like struct.
2031 let ctor_id = match struct_def.ctor_id {
2033 ccx.sess().bug("attempt to register a constructor of \
2034 a non-tuple-like struct")
2036 Some(ctor_id) => ctor_id,
2038 let parent = ccx.tcx.map.get_parent(id);
2039 let struct_item = ccx.tcx.map.expect_item(parent);
2040 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2041 let sym = exported_name(ccx,
2046 let llfn = register_fn(ccx, struct_item.span,
2048 set_inline_hint(llfn);
2053 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2058 // foreign items (extern fns and extern statics) don't have internal
2059 // linkage b/c that doesn't quite make sense. Otherwise items can
2060 // have internal linkage if they're not reachable.
2061 if !foreign && !ccx.reachable.contains(&id) {
2062 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2065 ccx.item_vals.borrow_mut().insert(id, val);
2069 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2070 m: &ast::Method) -> ValueRef {
2071 let mty = ty::node_id_to_type(ccx.tcx(), id);
2073 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2075 let llfn = register_fn(ccx, m.span, sym, id, mty);
2076 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2080 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2082 return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2086 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2087 -> encoder::EncodeParams<'r> {
2088 encoder::EncodeParams {
2089 diag: cx.sess().diagnostic(),
2091 reexports2: &cx.exp_map2,
2092 item_symbols: &cx.item_symbols,
2093 non_inlineable_statics: &cx.non_inlineable_statics,
2094 link_meta: &cx.link_meta,
2095 cstore: &cx.sess().cstore,
2096 encode_inlined_item: ie,
2100 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2103 if !cx.sess().building_library.get() {
2107 let encode_inlined_item: encoder::EncodeInlinedItem =
2108 |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2110 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2111 let metadata = encoder::encode_metadata(encode_parms, krate);
2112 let compressed = encoder::metadata_encoding_version +
2113 match flate::deflate_bytes(metadata.as_slice()) {
2114 Some(compressed) => compressed,
2115 None => cx.sess().fatal(format!("failed to compress metadata", ))
2117 let llmeta = C_bytes(cx, compressed);
2118 let llconst = C_struct(cx, [llmeta], false);
2119 let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2120 cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2121 let llglobal = name.with_c_str(|buf| {
2123 llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2127 llvm::LLVMSetInitializer(llglobal, llconst);
2128 cx.sess().targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2129 llvm::LLVMSetSection(llglobal, buf)
2135 pub fn trans_crate(krate: ast::Crate,
2136 analysis: CrateAnalysis,
2137 output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2138 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, .. } = analysis;
2140 // Before we touch LLVM, make sure that multithreading is enabled.
2142 use sync::one::{Once, ONCE_INIT};
2143 static mut INIT: Once = ONCE_INIT;
2144 static mut POISONED: bool = false;
2146 if llvm::LLVMStartMultithreaded() != 1 {
2147 // use an extra bool to make sure that all future usage of LLVM
2148 // cannot proceed despite the Once not running more than once.
2154 tcx.sess.bug("couldn't enable multi-threaded LLVM");
2158 let link_meta = link::build_link_meta(&krate, output.out_filestem);
2160 // Append ".rs" to crate name as LLVM module identifier.
2162 // LLVM code generator emits a ".file filename" directive
2163 // for ELF backends. Value of the "filename" is set as the
2164 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
2165 // crashes if the module identifer is same as other symbols
2166 // such as a function name in the module.
2167 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2168 let llmod_id = link_meta.crateid.name + ".rs";
2170 let ccx = CrateContext::new(llmod_id, tcx, exp_map2,
2171 Sha256::new(), link_meta, reachable);
2173 let _icx = push_ctxt("text");
2174 trans_mod(&ccx, &krate.module);
2177 glue::emit_tydescs(&ccx);
2178 if ccx.sess().opts.debuginfo != NoDebugInfo {
2179 debuginfo::finalize(&ccx);
2182 // Translate the metadata.
2183 let metadata = write_metadata(&ccx, &krate);
2184 if ccx.sess().trans_stats() {
2185 println!("--- trans stats ---");
2186 println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2187 println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2188 println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2189 println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2191 println!("n_fns: {}", ccx.stats.n_fns.get());
2192 println!("n_monos: {}", ccx.stats.n_monos.get());
2193 println!("n_inlines: {}", ccx.stats.n_inlines.get());
2194 println!("n_closures: {}", ccx.stats.n_closures.get());
2195 println!("fn stats:");
2196 ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2197 insns_b.cmp(&insns_a)
2199 for tuple in ccx.stats.fn_stats.borrow().iter() {
2201 (ref name, ms, insns) => {
2202 println!("{} insns, {} ms, {}", insns, ms, *name);
2207 if ccx.sess().count_llvm_insns() {
2208 for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2209 println!("{:7u} {}", *v, *k);
2213 let llcx = ccx.llcx;
2214 let link_meta = ccx.link_meta.clone();
2215 let llmod = ccx.llmod;
2217 let mut reachable: Vec<~str> = ccx.reachable.iter().filter_map(|id| {
2218 ccx.item_symbols.borrow().find(id).map(|s| s.to_owned())
2221 // Make sure that some other crucial symbols are not eliminated from the
2222 // module. This includes the main function, the crate map (used for debug
2223 // log settings and I/O), and finally the curious rust_stack_exhausted
2224 // symbol. This symbol is required for use by the libmorestack library that
2225 // we link in, so we must ensure that this symbol is not internalized (if
2226 // defined in the crate).
2227 reachable.push("main".to_owned());
2228 reachable.push("rust_stack_exhausted".to_owned());
2230 // referenced from .eh_frame section on some platforms
2231 reachable.push("rust_eh_personality".to_owned());
2232 reachable.push("rust_eh_personality_catch".to_owned()); // referenced from rt/rust_try.ll
2234 let metadata_module = ccx.metadata_llmod;
2236 (ccx.tcx, CrateTranslation {
2240 metadata_module: metadata_module,
2242 reachable: reachable,