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::config::{NoDebugInfo, FullDebugInfo};
32 use driver::driver::{CrateAnalysis, CrateTranslation, ModuleTranslation};
33 use driver::session::Session;
35 use llvm::{BasicBlockRef, ModuleRef, ValueRef, Vector, get_param};
37 use metadata::{csearch, encoder, loader};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
42 use middle::subst::Subst;
43 use middle::trans::_match;
44 use middle::trans::adt;
45 use middle::trans::build::*;
46 use middle::trans::builder::{Builder, noname};
47 use middle::trans::callee;
48 use middle::trans::cleanup::{CleanupMethods, ScopeId};
49 use middle::trans::cleanup;
50 use middle::trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_integral, C_nil};
51 use middle::trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_uint, C_undef};
52 use middle::trans::common::{CrateContext, ExternMap, FunctionContext};
53 use middle::trans::common::{NodeInfo, Result, SubstP, monomorphize_type};
54 use middle::trans::common::{node_id_type, param_substs, return_type_is_void};
55 use middle::trans::common::{tydesc_info, type_is_immediate};
56 use middle::trans::common::{type_is_zero_size, val_ty};
57 use middle::trans::common;
58 use middle::trans::consts;
59 use middle::trans::context::SharedCrateContext;
60 use middle::trans::controlflow;
61 use middle::trans::datum;
62 use middle::trans::debuginfo;
63 use middle::trans::expr;
64 use middle::trans::foreign;
65 use middle::trans::glue;
66 use middle::trans::inline;
67 use middle::trans::intrinsic;
68 use middle::trans::machine;
69 use middle::trans::machine::{llsize_of, llsize_of_real, llalign_of_min};
70 use middle::trans::meth;
71 use middle::trans::monomorphize;
72 use middle::trans::tvec;
73 use middle::trans::type_::Type;
74 use middle::trans::type_of;
75 use middle::trans::type_of::*;
76 use middle::trans::value::Value;
79 use util::common::indenter;
80 use util::ppaux::{Repr, ty_to_string};
81 use util::sha2::Sha256;
82 use util::nodemap::NodeMap;
84 use arena::TypedArena;
85 use libc::{c_uint, uint64_t};
86 use std::c_str::ToCStr;
87 use std::cell::{Cell, RefCell};
88 use std::collections::HashSet;
90 use std::{i8, i16, i32, i64};
91 use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel, Rust, RustCall};
92 use syntax::abi::{RustIntrinsic, Abi, OsWindows};
93 use syntax::ast_util::{local_def, is_local};
94 use syntax::attr::AttrMetaMethods;
96 use syntax::codemap::Span;
97 use syntax::parse::token::InternedString;
98 use syntax::visit::Visitor;
100 use syntax::{ast, ast_util, ast_map};
104 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
106 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
107 match task_local_insn_key.get() {
108 Some(ctx) => blk(ctx.borrow().as_slice()),
113 pub fn init_insn_ctxt() {
114 task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
117 pub struct _InsnCtxt {
118 _cannot_construct_outside_of_this_module: ()
122 impl Drop for _InsnCtxt {
124 match task_local_insn_key.get() {
125 Some(ctx) => { ctx.borrow_mut().pop(); }
131 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
132 debug!("new InsnCtxt: {}", s);
133 match task_local_insn_key.get() {
134 Some(ctx) => ctx.borrow_mut().push(s),
137 _InsnCtxt { _cannot_construct_outside_of_this_module: () }
140 pub struct StatRecorder<'a, 'tcx: 'a> {
141 ccx: &'a CrateContext<'a, 'tcx>,
142 name: Option<String>,
147 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
148 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String)
149 -> StatRecorder<'a, 'tcx> {
150 let start = if ccx.sess().trans_stats() {
151 time::precise_time_ns()
155 let istart = ccx.stats().n_llvm_insns.get();
166 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
168 if self.ccx.sess().trans_stats() {
169 let end = time::precise_time_ns();
170 let elapsed = ((end - self.start) / 1_000_000) as uint;
171 let iend = self.ccx.stats().n_llvm_insns.get();
172 self.ccx.stats().fn_stats.borrow_mut().push((self.name.take().unwrap(),
174 iend - self.istart));
175 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
176 // Reset LLVM insn count to avoid compound costs.
177 self.ccx.stats().n_llvm_insns.set(self.istart);
182 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
183 pub fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
184 ty: Type, output: ty::t) -> ValueRef {
186 let llfn: ValueRef = name.with_c_str(|buf| {
188 llvm::LLVMGetOrInsertFunction(ccx.llmod(), buf, ty.to_ref())
192 match ty::get(output).sty {
193 // functions returning bottom may unwind, but can never return normally
196 llvm::LLVMAddFunctionAttribute(llfn,
197 llvm::FunctionIndex as c_uint,
198 llvm::NoReturnAttribute as uint64_t)
204 if ccx.tcx().sess.opts.cg.no_redzone {
206 llvm::LLVMAddFunctionAttribute(llfn,
207 llvm::FunctionIndex as c_uint,
208 llvm::NoRedZoneAttribute as uint64_t)
212 llvm::SetFunctionCallConv(llfn, cc);
213 // Function addresses in Rust are never significant, allowing functions to be merged.
214 llvm::SetUnnamedAddr(llfn, true);
216 if ccx.is_split_stack_supported() {
217 set_split_stack(llfn);
223 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
224 pub fn decl_cdecl_fn(ccx: &CrateContext,
227 output: ty::t) -> ValueRef {
228 decl_fn(ccx, name, llvm::CCallConv, ty, output)
231 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
232 pub fn get_extern_fn(ccx: &CrateContext,
233 externs: &mut ExternMap,
239 match externs.find_equiv(&name) {
240 Some(n) => return *n,
243 let f = decl_fn(ccx, name, cc, ty, output);
244 externs.insert(name.to_string(), f);
248 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
249 match ccx.externs().borrow().find_equiv(&name) {
250 Some(n) => return *n,
254 let f = decl_rust_fn(ccx, fn_ty, name);
256 csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
257 set_llvm_fn_attrs(attrs.as_slice(), f)
260 ccx.externs().borrow_mut().insert(name.to_string(), f);
264 pub fn self_type_for_unboxed_closure(ccx: &CrateContext,
265 closure_id: ast::DefId)
267 let unboxed_closure_type = ty::mk_unboxed_closure(ccx.tcx(),
270 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
271 let unboxed_closure = unboxed_closures.get(&closure_id);
272 match unboxed_closure.kind {
273 ty::FnUnboxedClosureKind => {
274 ty::mk_imm_rptr(ccx.tcx(), ty::ReStatic, unboxed_closure_type)
276 ty::FnMutUnboxedClosureKind => {
277 ty::mk_mut_rptr(ccx.tcx(), ty::ReStatic, unboxed_closure_type)
279 ty::FnOnceUnboxedClosureKind => unboxed_closure_type,
283 pub fn kind_for_unboxed_closure(ccx: &CrateContext, closure_id: ast::DefId)
284 -> ty::UnboxedClosureKind {
285 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
286 unboxed_closures.get(&closure_id).kind
289 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
290 let (inputs, output, abi, env) = match ty::get(fn_ty).sty {
291 ty::ty_bare_fn(ref f) => {
292 (f.sig.inputs.clone(), f.sig.output, f.abi, None)
294 ty::ty_closure(ref f) => {
295 (f.sig.inputs.clone(), f.sig.output, f.abi, Some(Type::i8p(ccx)))
297 ty::ty_unboxed_closure(closure_did, _) => {
298 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
299 let unboxed_closure = unboxed_closures.get(&closure_did);
300 let function_type = unboxed_closure.closure_type.clone();
301 let self_type = self_type_for_unboxed_closure(ccx, closure_did);
302 let llenvironment_type = type_of_explicit_arg(ccx, self_type);
303 (function_type.sig.inputs.clone(),
304 function_type.sig.output,
306 Some(llenvironment_type))
308 _ => fail!("expected closure or fn")
311 let llfty = type_of_rust_fn(ccx, env, inputs.as_slice(), output, abi);
312 debug!("decl_rust_fn(input count={},type={})",
314 ccx.tn().type_to_string(llfty));
316 let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, output);
317 let attrs = get_fn_llvm_attributes(ccx, fn_ty);
318 attrs.apply_llfn(llfn);
323 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
324 let llfn = decl_rust_fn(ccx, fn_ty, name);
325 llvm::SetLinkage(llfn, llvm::InternalLinkage);
329 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
330 name: &str, ty: Type) -> ValueRef {
331 match externs.find_equiv(&name) {
332 Some(n) => return *n,
336 let c = name.with_c_str(|buf| {
337 llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
339 externs.insert(name.to_string(), c);
344 // Returns a pointer to the body for the box. The box may be an opaque
345 // box. The result will be casted to the type of body_t, if it is statically
347 pub fn at_box_body(bcx: Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
348 let _icx = push_ctxt("at_box_body");
350 let ty = Type::at_box(ccx, type_of(ccx, body_t));
351 let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
352 GEPi(bcx, boxptr, [0u, abi::box_field_body])
355 fn require_alloc_fn(bcx: Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
356 match bcx.tcx().lang_items.require(it) {
359 bcx.sess().fatal(format!("allocation of `{}` {}",
360 bcx.ty_to_string(info_ty),
366 // The following malloc_raw_dyn* functions allocate a box to contain
367 // a given type, but with a potentially dynamic size.
369 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
374 -> Result<'blk, 'tcx> {
375 let _icx = push_ctxt("malloc_raw_exchange");
378 let r = callee::trans_lang_call(bcx,
379 require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
383 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
386 pub fn malloc_raw_dyn_proc<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
387 t: ty::t, alloc_fn: LangItem)
388 -> Result<'blk, 'tcx> {
389 let _icx = push_ctxt("malloc_raw_dyn_proc");
392 let langcall = require_alloc_fn(bcx, t, alloc_fn);
394 // Grab the TypeRef type of ptr_ty.
395 let ptr_ty = ty::mk_uniq(bcx.tcx(), t);
396 let ptr_llty = type_of(ccx, ptr_ty);
398 let llty = type_of(bcx.ccx(), t);
399 let size = llsize_of(bcx.ccx(), llty);
400 let llalign = C_uint(ccx, llalign_of_min(bcx.ccx(), llty) as uint);
403 let drop_glue = glue::get_drop_glue(ccx, ty::mk_uniq(bcx.tcx(), t));
404 let r = callee::trans_lang_call(
408 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
413 Result::new(r.bcx, PointerCast(r.bcx, r.val, ptr_llty))
417 pub fn malloc_raw_dyn_managed<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
421 -> Result<'blk, 'tcx> {
422 let _icx = push_ctxt("malloc_raw_dyn_managed");
425 let langcall = require_alloc_fn(bcx, t, alloc_fn);
427 // Grab the TypeRef type of box_ptr_ty.
428 let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
429 let llty = type_of(ccx, box_ptr_ty);
430 let llalign = C_uint(ccx, type_of::align_of(ccx, box_ptr_ty) as uint);
433 let drop_glue = glue::get_drop_glue(ccx, t);
434 let r = callee::trans_lang_call(
438 PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
443 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
446 // Type descriptor and type glue stuff
448 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
449 match ccx.tydescs().borrow().find(&t) {
450 Some(inf) => return inf.clone(),
454 ccx.stats().n_static_tydescs.set(ccx.stats().n_static_tydescs.get() + 1u);
455 let inf = Rc::new(glue::declare_tydesc(ccx, t));
457 ccx.tydescs().borrow_mut().insert(t, inf.clone());
461 #[allow(dead_code)] // useful
462 pub fn set_optimize_for_size(f: ValueRef) {
463 llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
466 pub fn set_no_inline(f: ValueRef) {
467 llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
470 #[allow(dead_code)] // useful
471 pub fn set_no_unwind(f: ValueRef) {
472 llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
475 // Tell LLVM to emit the information necessary to unwind the stack for the
477 pub fn set_uwtable(f: ValueRef) {
478 llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
481 pub fn set_inline_hint(f: ValueRef) {
482 llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
485 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
487 // Set the inline hint if there is one
488 match find_inline_attr(attrs) {
489 InlineHint => set_inline_hint(llfn),
490 InlineAlways => set_always_inline(llfn),
491 InlineNever => set_no_inline(llfn),
492 InlineNone => { /* fallthrough */ }
495 // Add the no-split-stack attribute if requested
496 if contains_name(attrs, "no_split_stack") {
497 unset_split_stack(llfn);
500 if contains_name(attrs, "cold") {
502 llvm::LLVMAddFunctionAttribute(llfn,
503 llvm::FunctionIndex as c_uint,
504 llvm::ColdAttribute as uint64_t)
509 pub fn set_always_inline(f: ValueRef) {
510 llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
513 pub fn set_split_stack(f: ValueRef) {
514 "split-stack".with_c_str(|buf| {
515 unsafe { llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
519 pub fn unset_split_stack(f: ValueRef) {
520 "split-stack".with_c_str(|buf| {
521 unsafe { llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
525 // Double-check that we never ask LLVM to declare the same symbol twice. It
526 // silently mangles such symbols, breaking our linkage model.
527 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
528 if ccx.all_llvm_symbols().borrow().contains(&sym) {
529 ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
531 ccx.all_llvm_symbols().borrow_mut().insert(sym);
535 pub fn get_res_dtor(ccx: &CrateContext,
538 parent_id: ast::DefId,
539 substs: &subst::Substs)
541 let _icx = push_ctxt("trans_res_dtor");
542 let did = inline::maybe_instantiate_inline(ccx, did);
544 if !substs.types.is_empty() {
545 assert_eq!(did.krate, ast::LOCAL_CRATE);
547 // Since we're in trans we don't care for any region parameters
548 let ref substs = subst::Substs::erased(substs.types.clone());
550 let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
551 let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
554 } else if did.krate == ast::LOCAL_CRATE {
555 get_item_val(ccx, did.node)
558 let name = csearch::get_symbol(&ccx.sess().cstore, did);
559 let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
560 let llty = type_of_dtor(ccx, class_ty);
561 let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
562 [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
564 &mut *ccx.externs().borrow_mut(),
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 pub fn compare_scalar_types<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
592 -> Result<'blk, 'tcx> {
593 let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
595 match ty::get(t).sty {
596 ty::ty_nil => f(nil_type),
597 ty::ty_bool | ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
598 ty::ty_ptr(mt) if ty::type_is_sized(cx.tcx(), mt.ty) => f(unsigned_int),
599 ty::ty_int(_) => f(signed_int),
600 ty::ty_float(_) => f(floating_point),
601 // Should never get here, because t is scalar.
602 _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
607 // A helper function to do the actual comparison of scalar values.
608 pub fn compare_scalar_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
614 let _icx = push_ctxt("compare_scalar_values");
615 fn die(cx: Block) -> ! {
616 cx.sess().bug("compare_scalar_values: must be a comparison operator");
620 // We don't need to do actual comparisons for nil.
621 // () == () holds but () < () does not.
623 ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(cx.ccx(), true),
624 ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(cx.ccx(), false),
625 // refinements would be nice
631 ast::BiEq => llvm::RealOEQ,
632 ast::BiNe => llvm::RealUNE,
633 ast::BiLt => llvm::RealOLT,
634 ast::BiLe => llvm::RealOLE,
635 ast::BiGt => llvm::RealOGT,
636 ast::BiGe => llvm::RealOGE,
639 return FCmp(cx, cmp, lhs, rhs);
643 ast::BiEq => llvm::IntEQ,
644 ast::BiNe => llvm::IntNE,
645 ast::BiLt => llvm::IntSLT,
646 ast::BiLe => llvm::IntSLE,
647 ast::BiGt => llvm::IntSGT,
648 ast::BiGe => llvm::IntSGE,
651 return ICmp(cx, cmp, lhs, rhs);
655 ast::BiEq => llvm::IntEQ,
656 ast::BiNe => llvm::IntNE,
657 ast::BiLt => llvm::IntULT,
658 ast::BiLe => llvm::IntULE,
659 ast::BiGt => llvm::IntUGT,
660 ast::BiGe => llvm::IntUGE,
663 return ICmp(cx, cmp, lhs, rhs);
668 pub fn compare_simd_types(
676 match ty::get(t).sty {
678 // The comparison operators for floating point vectors are challenging.
679 // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
680 // then bitcast to a floating point vector, the result will be `-NaN`
681 // for each truth value. Because of this they are unsupported.
682 cx.sess().bug("compare_simd_types: comparison operators \
683 not supported for floating point SIMD types")
685 ty::ty_uint(_) | ty::ty_int(_) => {
687 ast::BiEq => llvm::IntEQ,
688 ast::BiNe => llvm::IntNE,
689 ast::BiLt => llvm::IntSLT,
690 ast::BiLe => llvm::IntSLE,
691 ast::BiGt => llvm::IntSGT,
692 ast::BiGe => llvm::IntSGE,
693 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
695 let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
696 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
697 // to get the correctly sized type. This will compile to a single instruction
698 // once the IR is converted to assembly if the SIMD instruction is supported
699 // by the target architecture.
700 SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
702 _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
706 pub type val_and_ty_fn<'a, 'blk, 'tcx> =
707 |Block<'blk, 'tcx>, ValueRef, ty::t|: 'a -> Block<'blk, 'tcx>;
709 // Iterates through the elements of a structural type.
710 pub fn iter_structural_ty<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
713 f: val_and_ty_fn<'a, 'blk, 'tcx>)
714 -> Block<'blk, 'tcx> {
715 let _icx = push_ctxt("iter_structural_ty");
717 fn iter_variant<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
720 variant: &ty::VariantInfo,
721 substs: &subst::Substs,
722 f: val_and_ty_fn<'a, 'blk, 'tcx>)
723 -> Block<'blk, 'tcx> {
724 let _icx = push_ctxt("iter_variant");
728 for (i, &arg) in variant.args.iter().enumerate() {
730 adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
731 arg.subst(tcx, substs));
736 let (data_ptr, info) = if ty::type_is_sized(cx.tcx(), t) {
739 let data = GEPi(cx, av, [0, abi::slice_elt_base]);
740 let info = GEPi(cx, av, [0, abi::slice_elt_len]);
741 (Load(cx, data), Some(Load(cx, info)))
745 match ty::get(t).sty {
746 ty::ty_struct(..) => {
747 let repr = adt::represent_type(cx.ccx(), t);
748 expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
749 for (i, field_ty) in field_tys.iter().enumerate() {
750 let field_ty = field_ty.mt.ty;
751 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, discr, i);
753 let val = if ty::type_is_sized(cx.tcx(), field_ty) {
756 let boxed_ty = ty::mk_open(cx.tcx(), field_ty);
757 let scratch = datum::rvalue_scratch_datum(cx, boxed_ty, "__fat_ptr_iter");
758 Store(cx, llfld_a, GEPi(cx, scratch.val, [0, abi::slice_elt_base]));
759 Store(cx, info.unwrap(), GEPi(cx, scratch.val, [0, abi::slice_elt_len]));
762 cx = f(cx, val, field_ty);
766 ty::ty_unboxed_closure(def_id, _) => {
767 let repr = adt::represent_type(cx.ccx(), t);
768 let upvars = ty::unboxed_closure_upvars(cx.tcx(), def_id);
769 for (i, upvar) in upvars.iter().enumerate() {
770 let llupvar = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
771 cx = f(cx, llupvar, upvar.ty);
774 ty::ty_vec(_, Some(n)) => {
775 let (base, len) = tvec::get_fixed_base_and_len(cx, data_ptr, n);
776 let unit_ty = ty::sequence_element_type(cx.tcx(), t);
777 cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
779 ty::ty_tup(ref args) => {
780 let repr = adt::represent_type(cx.ccx(), t);
781 for (i, arg) in args.iter().enumerate() {
782 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
783 cx = f(cx, llfld_a, *arg);
786 ty::ty_enum(tid, ref substs) => {
790 let repr = adt::represent_type(ccx, t);
791 let variants = ty::enum_variants(ccx.tcx(), tid);
792 let n_variants = (*variants).len();
794 // NB: we must hit the discriminant first so that structural
795 // comparison know not to proceed when the discriminants differ.
797 match adt::trans_switch(cx, &*repr, av) {
798 (_match::Single, None) => {
799 cx = iter_variant(cx, &*repr, av, &**variants.get(0),
802 (_match::Switch, Some(lldiscrim_a)) => {
803 cx = f(cx, lldiscrim_a, ty::mk_int());
804 let unr_cx = fcx.new_temp_block("enum-iter-unr");
806 let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
808 let next_cx = fcx.new_temp_block("enum-iter-next");
810 for variant in (*variants).iter() {
813 format!("enum-iter-variant-{}",
814 variant.disr_val.to_string().as_slice())
816 match adt::trans_case(cx, &*repr, variant.disr_val) {
817 _match::SingleResult(r) => {
818 AddCase(llswitch, r.val, variant_cx.llbb)
820 _ => ccx.sess().unimpl("value from adt::trans_case \
821 in iter_structural_ty")
824 iter_variant(variant_cx,
830 Br(variant_cx, next_cx.llbb);
834 _ => ccx.sess().unimpl("value from adt::trans_switch \
835 in iter_structural_ty")
838 _ => cx.sess().unimpl("type in iter_structural_ty")
843 pub fn cast_shift_expr_rhs(cx: Block,
848 cast_shift_rhs(op, lhs, rhs,
849 |a,b| Trunc(cx, a, b),
850 |a,b| ZExt(cx, a, b))
853 pub fn cast_shift_const_rhs(op: ast::BinOp,
854 lhs: ValueRef, rhs: ValueRef) -> ValueRef {
855 cast_shift_rhs(op, lhs, rhs,
856 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
857 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
860 pub fn cast_shift_rhs(op: ast::BinOp,
863 trunc: |ValueRef, Type| -> ValueRef,
864 zext: |ValueRef, Type| -> ValueRef)
866 // Shifts may have any size int on the rhs
868 if ast_util::is_shift_binop(op) {
869 let mut rhs_llty = val_ty(rhs);
870 let mut lhs_llty = val_ty(lhs);
871 if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
872 if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
873 let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
874 let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
877 } else if lhs_sz > rhs_sz {
878 // FIXME (#1877: If shifting by negative
879 // values becomes not undefined then this is wrong.
890 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(
891 cx: Block<'blk, 'tcx>,
897 -> Block<'blk, 'tcx> {
898 let (zero_text, overflow_text) = if divrem == ast::BiDiv {
899 ("attempted to divide by zero",
900 "attempted to divide with overflow")
902 ("attempted remainder with a divisor of zero",
903 "attempted remainder with overflow")
905 let (is_zero, is_signed) = match ty::get(rhs_t).sty {
907 let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
908 (ICmp(cx, llvm::IntEQ, rhs, zero), true)
911 let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
912 (ICmp(cx, llvm::IntEQ, rhs, zero), false)
915 cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
916 ty_to_string(cx.tcx(), rhs_t)).as_slice());
919 let bcx = with_cond(cx, is_zero, |bcx| {
920 controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
923 // To quote LLVM's documentation for the sdiv instruction:
925 // Division by zero leads to undefined behavior. Overflow also leads
926 // to undefined behavior; this is a rare case, but can occur, for
927 // example, by doing a 32-bit division of -2147483648 by -1.
929 // In order to avoid undefined behavior, we perform runtime checks for
930 // signed division/remainder which would trigger overflow. For unsigned
931 // integers, no action beyond checking for zero need be taken.
933 let (llty, min) = match ty::get(rhs_t).sty {
935 let llty = Type::int_from_ty(cx.ccx(), t);
937 ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
938 ast::TyI => i64::MIN as u64,
939 ast::TyI8 => i8::MIN as u64,
940 ast::TyI16 => i16::MIN as u64,
941 ast::TyI32 => i32::MIN as u64,
942 ast::TyI64 => i64::MIN as u64,
948 let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
949 C_integral(llty, -1, false));
950 with_cond(bcx, minus_one, |bcx| {
951 let is_min = ICmp(bcx, llvm::IntEQ, lhs,
952 C_integral(llty, min, true));
953 with_cond(bcx, is_min, |bcx| {
954 controlflow::trans_fail(bcx, span,
955 InternedString::new(overflow_text))
963 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
964 let name = csearch::get_symbol(&ccx.sess().cstore, did);
965 match ty::get(t).sty {
966 ty::ty_bare_fn(ref fn_ty) => {
967 match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
968 ccx.sess().targ_cfg.arch) {
969 Some(Rust) | Some(RustCall) => {
970 get_extern_rust_fn(ccx, t, name.as_slice(), did)
972 Some(RustIntrinsic) => {
973 ccx.sess().bug("unexpected intrinsic in trans_external_path")
976 foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
977 name.as_slice(), None)
981 ty::ty_closure(_) => {
982 get_extern_rust_fn(ccx, t, name.as_slice(), did)
985 let llty = type_of(ccx, t);
986 get_extern_const(&mut *ccx.externs().borrow_mut(),
994 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
996 llargs: Vec<ValueRef> ,
998 call_info: Option<NodeInfo>,
999 // FIXME(15064) is_lang_item is a horrible hack, please remove it
1000 // at the soonest opportunity.
1002 -> (ValueRef, Block<'blk, 'tcx>) {
1003 let _icx = push_ctxt("invoke_");
1004 if bcx.unreachable.get() {
1005 return (C_null(Type::i8(bcx.ccx())), bcx);
1008 // FIXME(15064) Lang item methods may (in the reflect case) not have proper
1009 // types, so doing an attribute lookup will fail.
1010 let attributes = if is_lang_item {
1011 llvm::AttrBuilder::new()
1013 get_fn_llvm_attributes(bcx.ccx(), fn_ty)
1016 match bcx.opt_node_id {
1018 debug!("invoke at ???");
1021 debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
1025 if need_invoke(bcx) {
1026 debug!("invoking {} at {}", llfn, bcx.llbb);
1027 for &llarg in llargs.iter() {
1028 debug!("arg: {}", llarg);
1030 let normal_bcx = bcx.fcx.new_temp_block("normal-return");
1031 let landing_pad = bcx.fcx.get_landing_pad();
1034 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
1035 None => debuginfo::clear_source_location(bcx.fcx)
1038 let llresult = Invoke(bcx,
1044 return (llresult, normal_bcx);
1046 debug!("calling {} at {}", llfn, bcx.llbb);
1047 for &llarg in llargs.iter() {
1048 debug!("arg: {}", llarg);
1052 Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
1053 None => debuginfo::clear_source_location(bcx.fcx)
1056 let llresult = Call(bcx, llfn, llargs.as_slice(), Some(attributes));
1057 return (llresult, bcx);
1061 pub fn need_invoke(bcx: Block) -> bool {
1062 if bcx.sess().no_landing_pads() {
1066 // Avoid using invoke if we are already inside a landing pad.
1071 bcx.fcx.needs_invoke()
1074 pub fn load_if_immediate(cx: Block, v: ValueRef, t: ty::t) -> ValueRef {
1075 let _icx = push_ctxt("load_if_immediate");
1076 if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
1080 pub fn load_ty(cx: Block, ptr: ValueRef, t: ty::t) -> ValueRef {
1082 * Helper for loading values from memory. Does the necessary conversion if
1083 * the in-memory type differs from the type used for SSA values. Also
1084 * handles various special cases where the type gives us better information
1085 * about what we are loading.
1087 if type_is_zero_size(cx.ccx(), t) {
1088 C_undef(type_of::type_of(cx.ccx(), t))
1089 } else if ty::type_is_bool(t) {
1090 Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
1091 } else if ty::type_is_char(t) {
1092 // a char is a Unicode codepoint, and so takes values from 0
1093 // to 0x10FFFF inclusive only.
1094 LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1100 pub fn store_ty(cx: Block, v: ValueRef, dst: ValueRef, t: ty::t) {
1102 * Helper for storing values in memory. Does the necessary conversion if
1103 * the in-memory type differs from the type used for SSA values.
1105 if ty::type_is_bool(t) {
1106 Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1112 pub fn ignore_lhs(_bcx: Block, local: &ast::Local) -> bool {
1113 match local.pat.node {
1114 ast::PatWild(ast::PatWildSingle) => true, _ => false
1118 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &ast::Local)
1119 -> Block<'blk, 'tcx> {
1120 debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
1121 let _indenter = indenter();
1122 let _icx = push_ctxt("init_local");
1123 _match::store_local(bcx, local)
1126 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1128 llbb: BasicBlockRef)
1129 -> Block<'blk, 'tcx> {
1130 common::BlockS::new(llbb, is_lpad, None, fcx)
1133 pub fn with_cond<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1135 f: |Block<'blk, 'tcx>| -> Block<'blk, 'tcx>)
1136 -> Block<'blk, 'tcx> {
1137 let _icx = push_ctxt("with_cond");
1139 let next_cx = fcx.new_temp_block("next");
1140 let cond_cx = fcx.new_temp_block("cond");
1141 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1142 let after_cx = f(cond_cx);
1143 if !after_cx.terminated.get() {
1144 Br(after_cx, next_cx.llbb);
1149 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
1150 if cx.sess().opts.optimize == config::No {
1154 let _icx = push_ctxt("lifetime_start");
1157 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
1158 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1159 let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
1160 Call(cx, lifetime_start, [llsize, ptr], None);
1163 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
1164 if cx.sess().opts.optimize == config::No {
1168 let _icx = push_ctxt("lifetime_end");
1171 let llsize = C_u64(ccx, machine::llsize_of_alloc(ccx, val_ty(ptr).element_type()));
1172 let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1173 let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
1174 Call(cx, lifetime_end, [llsize, ptr], None);
1177 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1178 let _icx = push_ctxt("call_memcpy");
1180 let key = match ccx.sess().targ_cfg.arch {
1181 X86 | Arm | Mips | Mipsel => "llvm.memcpy.p0i8.p0i8.i32",
1182 X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1184 let memcpy = ccx.get_intrinsic(&key);
1185 let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1186 let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1187 let size = IntCast(cx, n_bytes, ccx.int_type());
1188 let align = C_i32(ccx, align as i32);
1189 let volatile = C_bool(ccx, false);
1190 Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], None);
1193 pub fn memcpy_ty(bcx: Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1194 let _icx = push_ctxt("memcpy_ty");
1195 let ccx = bcx.ccx();
1196 if ty::type_is_structural(t) {
1197 let llty = type_of::type_of(ccx, t);
1198 let llsz = llsize_of(ccx, llty);
1199 let llalign = type_of::align_of(ccx, t);
1200 call_memcpy(bcx, dst, src, llsz, llalign as u32);
1202 store_ty(bcx, Load(bcx, src), dst, t);
1206 pub fn zero_mem(cx: Block, llptr: ValueRef, t: ty::t) {
1207 if cx.unreachable.get() { return; }
1208 let _icx = push_ctxt("zero_mem");
1210 memzero(&B(bcx), llptr, t);
1213 // Always use this function instead of storing a zero constant to the memory
1214 // in question. If you store a zero constant, LLVM will drown in vreg
1215 // allocation for large data structures, and the generated code will be
1216 // awful. (A telltale sign of this is large quantities of
1217 // `mov [byte ptr foo],0` in the generated code.)
1218 fn memzero(b: &Builder, llptr: ValueRef, ty: ty::t) {
1219 let _icx = push_ctxt("memzero");
1222 let llty = type_of::type_of(ccx, ty);
1224 let intrinsic_key = match ccx.sess().targ_cfg.arch {
1225 X86 | Arm | Mips | Mipsel => "llvm.memset.p0i8.i32",
1226 X86_64 => "llvm.memset.p0i8.i64"
1229 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1230 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1231 let llzeroval = C_u8(ccx, 0);
1232 let size = machine::llsize_of(ccx, llty);
1233 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
1234 let volatile = C_bool(ccx, false);
1235 b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], None);
1238 pub fn alloc_ty(bcx: Block, t: ty::t, name: &str) -> ValueRef {
1239 let _icx = push_ctxt("alloc_ty");
1240 let ccx = bcx.ccx();
1241 let ty = type_of::type_of(ccx, t);
1242 assert!(!ty::type_has_params(t));
1243 let val = alloca(bcx, ty, name);
1247 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
1248 let p = alloca_no_lifetime(cx, ty, name);
1249 call_lifetime_start(cx, p);
1253 pub fn alloca_no_lifetime(cx: Block, ty: Type, name: &str) -> ValueRef {
1254 let _icx = push_ctxt("alloca");
1255 if cx.unreachable.get() {
1257 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1260 debuginfo::clear_source_location(cx.fcx);
1261 Alloca(cx, ty, name)
1264 pub fn alloca_zeroed(cx: Block, ty: ty::t, name: &str) -> ValueRef {
1265 let llty = type_of::type_of(cx.ccx(), ty);
1266 if cx.unreachable.get() {
1268 return llvm::LLVMGetUndef(llty.ptr_to().to_ref());
1271 let p = alloca_no_lifetime(cx, llty, name);
1272 let b = cx.fcx.ccx.builder();
1273 b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1278 pub fn arrayalloca(cx: Block, ty: Type, v: ValueRef) -> ValueRef {
1279 let _icx = push_ctxt("arrayalloca");
1280 if cx.unreachable.get() {
1282 return llvm::LLVMGetUndef(ty.to_ref());
1285 debuginfo::clear_source_location(cx.fcx);
1286 let p = ArrayAlloca(cx, ty, v);
1287 call_lifetime_start(cx, p);
1291 // Creates the alloca slot which holds the pointer to the slot for the final return value
1292 pub fn make_return_slot_pointer(fcx: &FunctionContext, output_type: ty::t) -> ValueRef {
1293 let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1295 // We create an alloca to hold a pointer of type `output_type`
1296 // which will hold the pointer to the right alloca which has the
1298 if fcx.needs_ret_allocas {
1299 // Let's create the stack slot
1300 let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1302 // and if we're using an out pointer, then store that in our newly made slot
1303 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1304 let outptr = get_param(fcx.llfn, 0);
1306 let b = fcx.ccx.builder();
1307 b.position_before(fcx.alloca_insert_pt.get().unwrap());
1308 b.store(outptr, slot);
1313 // But if there are no nested returns, we skip the indirection and have a single
1316 if type_of::return_uses_outptr(fcx.ccx, output_type) {
1317 get_param(fcx.llfn, 0)
1319 AllocaFcx(fcx, lloutputtype, "sret_slot")
1324 struct CheckForNestedReturnsVisitor {
1329 impl CheckForNestedReturnsVisitor {
1330 fn explicit() -> CheckForNestedReturnsVisitor {
1331 CheckForNestedReturnsVisitor { found: false, in_return: false }
1333 fn implicit() -> CheckForNestedReturnsVisitor {
1334 CheckForNestedReturnsVisitor { found: false, in_return: true }
1338 impl<'v> Visitor<'v> for CheckForNestedReturnsVisitor {
1339 fn visit_expr(&mut self, e: &ast::Expr) {
1341 ast::ExprRet(..) => {
1345 self.in_return = true;
1346 visit::walk_expr(self, e);
1347 self.in_return = false;
1350 _ => visit::walk_expr(self, e)
1355 fn has_nested_returns(tcx: &ty::ctxt, id: ast::NodeId) -> bool {
1356 match tcx.map.find(id) {
1357 Some(ast_map::NodeItem(i)) => {
1359 ast::ItemFn(_, _, _, _, ref blk) => {
1360 let mut explicit = CheckForNestedReturnsVisitor::explicit();
1361 let mut implicit = CheckForNestedReturnsVisitor::implicit();
1362 visit::walk_item(&mut explicit, &*i);
1363 visit::walk_expr_opt(&mut implicit, &blk.expr);
1364 explicit.found || implicit.found
1366 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1369 Some(ast_map::NodeTraitItem(trait_method)) => {
1370 match *trait_method {
1371 ast::ProvidedMethod(ref m) => {
1373 ast::MethDecl(_, _, _, _, _, _, ref blk, _) => {
1374 let mut explicit = CheckForNestedReturnsVisitor::explicit();
1375 let mut implicit = CheckForNestedReturnsVisitor::implicit();
1376 visit::walk_method_helper(&mut explicit, &**m);
1377 visit::walk_expr_opt(&mut implicit, &blk.expr);
1378 explicit.found || implicit.found
1380 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1383 ast::RequiredMethod(_) => {
1384 tcx.sess.bug("unexpected variant: required trait method \
1385 in has_nested_returns")
1389 Some(ast_map::NodeImplItem(ii)) => {
1391 ast::MethodImplItem(ref m) => {
1393 ast::MethDecl(_, _, _, _, _, _, ref blk, _) => {
1394 let mut explicit = CheckForNestedReturnsVisitor::explicit();
1395 let mut implicit = CheckForNestedReturnsVisitor::implicit();
1396 visit::walk_method_helper(&mut explicit, &**m);
1397 visit::walk_expr_opt(&mut implicit, &blk.expr);
1398 explicit.found || implicit.found
1400 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1405 Some(ast_map::NodeExpr(e)) => {
1407 ast::ExprFnBlock(_, _, ref blk) |
1408 ast::ExprProc(_, ref blk) |
1409 ast::ExprUnboxedFn(_, _, _, ref blk) => {
1410 let mut explicit = CheckForNestedReturnsVisitor::explicit();
1411 let mut implicit = CheckForNestedReturnsVisitor::implicit();
1412 visit::walk_expr(&mut explicit, e);
1413 visit::walk_expr_opt(&mut implicit, &blk.expr);
1414 explicit.found || implicit.found
1416 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1420 Some(ast_map::NodeVariant(..)) | Some(ast_map::NodeStructCtor(..)) => false,
1423 None if id == ast::DUMMY_NODE_ID => false,
1425 _ => tcx.sess.bug(format!("unexpected variant in has_nested_returns: {}",
1426 tcx.map.path_to_string(id)).as_slice())
1430 // NB: must keep 4 fns in sync:
1433 // - create_datums_for_fn_args.
1437 // Be warned! You must call `init_function` before doing anything with the
1438 // returned function context.
1439 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1444 param_substs: &'a param_substs,
1446 block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1447 -> FunctionContext<'a, 'tcx> {
1448 param_substs.validate();
1450 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1454 ccx.tcx().map.path_to_string(id).to_string()
1456 id, param_substs.repr(ccx.tcx()));
1458 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1459 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1460 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1461 let nested_returns = has_nested_returns(ccx.tcx(), id);
1463 let mut fcx = FunctionContext {
1466 llretslotptr: Cell::new(None),
1467 alloca_insert_pt: Cell::new(None),
1468 llreturn: Cell::new(None),
1469 needs_ret_allocas: nested_returns,
1470 personality: Cell::new(None),
1471 caller_expects_out_pointer: uses_outptr,
1472 llargs: RefCell::new(NodeMap::new()),
1473 lllocals: RefCell::new(NodeMap::new()),
1474 llupvars: RefCell::new(NodeMap::new()),
1476 param_substs: param_substs,
1478 block_arena: block_arena,
1480 debug_context: debug_context,
1481 scopes: RefCell::new(Vec::new())
1485 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1491 /// Performs setup on a newly created function, creating the entry scope block
1492 /// and allocating space for the return pointer.
1493 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1495 output_type: ty::t) -> Block<'a, 'tcx> {
1496 let entry_bcx = fcx.new_temp_block("entry-block");
1498 // Use a dummy instruction as the insertion point for all allocas.
1499 // This is later removed in FunctionContext::cleanup.
1500 fcx.alloca_insert_pt.set(Some(unsafe {
1501 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1502 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1505 // This shouldn't need to recompute the return type,
1506 // as new_fn_ctxt did it already.
1507 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1509 if !return_type_is_void(fcx.ccx, substd_output_type) {
1510 // If the function returns nil/bot, there is no real return
1511 // value, so do not set `llretslotptr`.
1512 if !skip_retptr || fcx.caller_expects_out_pointer {
1513 // Otherwise, we normally allocate the llretslotptr, unless we
1514 // have been instructed to skip it for immediate return
1516 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1523 // NB: must keep 4 fns in sync:
1526 // - create_datums_for_fn_args.
1530 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1531 use middle::trans::datum::{ByRef, ByValue};
1534 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1538 // work around bizarre resolve errors
1539 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1540 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1542 // create_datums_for_fn_args: creates rvalue datums for each of the
1543 // incoming function arguments. These will later be stored into
1544 // appropriate lvalue datums.
1545 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1547 -> Vec<RvalueDatum> {
1548 let _icx = push_ctxt("create_datums_for_fn_args");
1550 // Return an array wrapping the ValueRefs that we get from `get_param` for
1551 // each argument into datums.
1552 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1553 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1554 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1558 /// Creates rvalue datums for each of the incoming function arguments and
1559 /// tuples the arguments. These will later be stored into appropriate lvalue
1562 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1563 fn create_datums_for_fn_args_under_call_abi(
1565 arg_scope: cleanup::CustomScopeIndex,
1567 -> Vec<RvalueDatum> {
1568 let mut result = Vec::new();
1569 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1570 if i < arg_tys.len() - 1 {
1571 // Regular argument.
1572 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1573 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1578 // This is the last argument. Tuple it.
1579 match ty::get(arg_ty).sty {
1580 ty::ty_tup(ref tupled_arg_tys) => {
1581 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1584 datum::lvalue_scratch_datum(bcx,
1588 tuple_args_scope_id,
1593 for (j, &tupled_arg_ty) in
1594 tupled_arg_tys.iter().enumerate() {
1596 get_param(bcx.fcx.llfn,
1597 bcx.fcx.arg_pos(i + j) as c_uint);
1598 let lldest = GEPi(bcx, llval, [0, j]);
1599 let datum = datum::Datum::new(
1602 arg_kind(bcx.fcx, tupled_arg_ty));
1603 bcx = datum.store_to(bcx, lldest);
1607 let tuple = unpack_datum!(bcx,
1608 tuple.to_expr_datum()
1609 .to_rvalue_datum(bcx,
1614 let mode = datum::Rvalue::new(datum::ByValue);
1615 result.push(datum::Datum::new(C_nil(bcx.ccx()),
1620 bcx.tcx().sess.bug("last argument of a function with \
1621 `rust-call` ABI isn't a tuple?!")
1630 fn copy_args_to_allocas<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1631 arg_scope: cleanup::CustomScopeIndex,
1632 bcx: Block<'blk, 'tcx>,
1634 arg_datums: Vec<RvalueDatum> )
1635 -> Block<'blk, 'tcx> {
1636 debug!("copy_args_to_allocas");
1638 let _icx = push_ctxt("copy_args_to_allocas");
1641 let arg_scope_id = cleanup::CustomScope(arg_scope);
1643 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1644 // For certain mode/type combinations, the raw llarg values are passed
1645 // by value. However, within the fn body itself, we want to always
1646 // have all locals and arguments be by-ref so that we can cancel the
1647 // cleanup and for better interaction with LLVM's debug info. So, if
1648 // the argument would be passed by value, we store it into an alloca.
1649 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1650 // the event it's not truly needed.
1652 bcx = _match::store_arg(bcx, &*args[i].pat, arg_datum, arg_scope_id);
1654 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1655 debuginfo::create_argument_metadata(bcx, &args[i]);
1662 fn copy_unboxed_closure_args_to_allocas<'blk, 'tcx>(
1663 mut bcx: Block<'blk, 'tcx>,
1664 arg_scope: cleanup::CustomScopeIndex,
1666 arg_datums: Vec<RvalueDatum>,
1667 monomorphized_arg_types: &[ty::t])
1668 -> Block<'blk, 'tcx> {
1669 let _icx = push_ctxt("copy_unboxed_closure_args_to_allocas");
1670 let arg_scope_id = cleanup::CustomScope(arg_scope);
1672 assert_eq!(arg_datums.len(), 1);
1674 let arg_datum = arg_datums.move_iter().next().unwrap();
1676 // Untuple the rest of the arguments.
1679 arg_datum.to_lvalue_datum_in_scope(bcx,
1682 let empty = Vec::new();
1683 let untupled_arg_types = match ty::get(monomorphized_arg_types[0]).sty {
1684 ty::ty_tup(ref types) => types.as_slice(),
1685 ty::ty_nil => empty.as_slice(),
1687 bcx.tcx().sess.span_bug(args[0].pat.span,
1688 "first arg to `rust-call` ABI function \
1692 for j in range(0, args.len()) {
1693 let tuple_element_type = untupled_arg_types[j];
1694 let tuple_element_datum =
1695 tuple_datum.get_element(bcx,
1697 |llval| GEPi(bcx, llval, [0, j]));
1698 let tuple_element_datum = tuple_element_datum.to_expr_datum();
1699 let tuple_element_datum =
1701 tuple_element_datum.to_rvalue_datum(bcx,
1703 bcx = _match::store_arg(bcx,
1705 tuple_element_datum,
1708 if bcx.fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1709 debuginfo::create_argument_metadata(bcx, &args[j]);
1716 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1717 // and builds the return block.
1718 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1719 last_bcx: Block<'blk, 'tcx>,
1721 let _icx = push_ctxt("finish_fn");
1723 // This shouldn't need to recompute the return type,
1724 // as new_fn_ctxt did it already.
1725 let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1727 let ret_cx = match fcx.llreturn.get() {
1729 if !last_bcx.terminated.get() {
1730 Br(last_bcx, llreturn);
1732 raw_block(fcx, false, llreturn)
1736 build_return_block(fcx, ret_cx, substd_retty);
1737 debuginfo::clear_source_location(fcx);
1741 // Builds the return block for a function.
1742 pub fn build_return_block(fcx: &FunctionContext, ret_cx: Block, retty: ty::t) {
1743 if fcx.llretslotptr.get().is_none() ||
1744 (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1745 return RetVoid(ret_cx);
1748 let retslot = if fcx.needs_ret_allocas {
1749 Load(ret_cx, fcx.llretslotptr.get().unwrap())
1751 fcx.llretslotptr.get().unwrap()
1753 let retptr = Value(retslot);
1754 match retptr.get_dominating_store(ret_cx) {
1755 // If there's only a single store to the ret slot, we can directly return
1756 // the value that was stored and omit the store and the alloca
1758 let retval = s.get_operand(0).unwrap().get();
1759 s.erase_from_parent();
1761 if retptr.has_no_uses() {
1762 retptr.erase_from_parent();
1765 let retval = if ty::type_is_bool(retty) {
1766 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1771 if fcx.caller_expects_out_pointer {
1772 store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1773 return RetVoid(ret_cx);
1775 return Ret(ret_cx, retval);
1778 // Otherwise, copy the return value to the ret slot
1780 if fcx.caller_expects_out_pointer {
1781 memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1782 return RetVoid(ret_cx);
1784 return Ret(ret_cx, load_ty(ret_cx, retslot, retty));
1790 #[deriving(Clone, Eq, PartialEq)]
1791 pub enum IsUnboxedClosureFlag {
1796 // trans_closure: Builds an LLVM function out of a source function.
1797 // If the function closes over its environment a closure will be
1799 pub fn trans_closure(ccx: &CrateContext,
1803 param_substs: ¶m_substs,
1805 _attributes: &[ast::Attribute],
1806 arg_types: Vec<ty::t>,
1810 is_unboxed_closure: IsUnboxedClosureFlag,
1811 maybe_load_env: <'blk, 'tcx> |Block<'blk, 'tcx>, ScopeId|
1812 -> Block<'blk, 'tcx>) {
1813 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1815 let _icx = push_ctxt("trans_closure");
1816 set_uwtable(llfndecl);
1818 debug!("trans_closure(..., param_substs={})",
1819 param_substs.repr(ccx.tcx()));
1821 let arena = TypedArena::new();
1822 let fcx = new_fn_ctxt(ccx,
1830 let mut bcx = init_function(&fcx, false, output_type);
1832 // cleanup scope for the incoming arguments
1833 let arg_scope = fcx.push_custom_cleanup_scope();
1835 let block_ty = node_id_type(bcx, body.id);
1837 // Set up arguments to the function.
1838 let monomorphized_arg_types =
1840 .map(|at| monomorphize_type(bcx, *at))
1841 .collect::<Vec<_>>();
1842 for monomorphized_arg_type in monomorphized_arg_types.iter() {
1843 debug!("trans_closure: monomorphized_arg_type: {}",
1844 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1846 debug!("trans_closure: function lltype: {}",
1847 bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1849 let arg_datums = if abi != RustCall {
1850 create_datums_for_fn_args(&fcx,
1851 monomorphized_arg_types.as_slice())
1853 create_datums_for_fn_args_under_call_abi(
1856 monomorphized_arg_types.as_slice())
1859 bcx = match is_unboxed_closure {
1860 NotUnboxedClosure => {
1861 copy_args_to_allocas(&fcx,
1864 decl.inputs.as_slice(),
1867 IsUnboxedClosure => {
1868 copy_unboxed_closure_args_to_allocas(
1871 decl.inputs.as_slice(),
1873 monomorphized_arg_types.as_slice())
1877 bcx = maybe_load_env(bcx, cleanup::CustomScope(arg_scope));
1879 // Up until here, IR instructions for this function have explicitly not been annotated with
1880 // source code location, so we don't step into call setup code. From here on, source location
1881 // emitting should be enabled.
1882 debuginfo::start_emitting_source_locations(&fcx);
1884 let dest = match fcx.llretslotptr.get() {
1885 Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, block_ty, "iret_slot")),
1887 assert!(type_is_zero_size(bcx.ccx(), block_ty));
1892 // This call to trans_block is the place where we bridge between
1893 // translation calls that don't have a return value (trans_crate,
1894 // trans_mod, trans_item, et cetera) and those that do
1895 // (trans_block, trans_expr, et cetera).
1896 bcx = controlflow::trans_block(bcx, body, dest);
1899 expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1900 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1905 match fcx.llreturn.get() {
1907 Br(bcx, fcx.return_exit_block());
1908 fcx.pop_custom_cleanup_scope(arg_scope);
1911 // Microoptimization writ large: avoid creating a separate
1912 // llreturn basic block
1913 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1917 // Put return block after all other blocks.
1918 // This somewhat improves single-stepping experience in debugger.
1920 let llreturn = fcx.llreturn.get();
1921 for &llreturn in llreturn.iter() {
1922 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1926 // Insert the mandatory first few basic blocks before lltop.
1927 finish_fn(&fcx, bcx, output_type);
1930 // trans_fn: creates an LLVM function corresponding to a source language
1932 pub fn trans_fn(ccx: &CrateContext,
1936 param_substs: ¶m_substs,
1938 attrs: &[ast::Attribute]) {
1939 let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1940 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1941 let _icx = push_ctxt("trans_fn");
1942 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1943 let arg_types = ty::ty_fn_args(fn_ty);
1944 let output_type = ty::ty_fn_ret(fn_ty);
1945 let abi = ty::ty_fn_abi(fn_ty);
1961 pub fn trans_enum_variant(ccx: &CrateContext,
1962 _enum_id: ast::NodeId,
1963 variant: &ast::Variant,
1964 _args: &[ast::VariantArg],
1966 param_substs: ¶m_substs,
1967 llfndecl: ValueRef) {
1968 let _icx = push_ctxt("trans_enum_variant");
1970 trans_enum_variant_or_tuple_like_struct(
1978 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1981 args: callee::CallArgs,
1982 dest: expr::Dest) -> Result<'blk, 'tcx> {
1984 let ccx = bcx.fcx.ccx;
1985 let tcx = ccx.tcx();
1987 let result_ty = match ty::get(ctor_ty).sty {
1988 ty::ty_bare_fn(ref bft) => bft.sig.output,
1989 _ => ccx.sess().bug(
1990 format!("trans_enum_variant_constructor: \
1991 unexpected ctor return type {}",
1992 ctor_ty.repr(tcx)).as_slice())
1995 // Get location to store the result. If the user does not care about
1996 // the result, just make a stack slot
1997 let llresult = match dest {
1998 expr::SaveIn(d) => d,
2000 if !type_is_zero_size(ccx, result_ty) {
2001 alloc_ty(bcx, result_ty, "constructor_result")
2003 C_undef(type_of::type_of(ccx, result_ty))
2008 if !type_is_zero_size(ccx, result_ty) {
2010 callee::ArgExprs(exprs) => {
2011 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
2012 bcx = expr::trans_adt(bcx, result_ty, disr, fields.as_slice(),
2013 None, expr::SaveIn(llresult));
2015 _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
2019 // If the caller doesn't care about the result
2020 // drop the temporary we made
2021 let bcx = match dest {
2022 expr::SaveIn(_) => bcx,
2023 expr::Ignore => glue::drop_ty(bcx, llresult, result_ty)
2026 Result::new(bcx, llresult)
2029 pub fn trans_tuple_struct(ccx: &CrateContext,
2030 _fields: &[ast::StructField],
2031 ctor_id: ast::NodeId,
2032 param_substs: ¶m_substs,
2033 llfndecl: ValueRef) {
2034 let _icx = push_ctxt("trans_tuple_struct");
2036 trans_enum_variant_or_tuple_like_struct(
2044 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
2045 ctor_id: ast::NodeId,
2047 param_substs: ¶m_substs,
2048 llfndecl: ValueRef) {
2049 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2050 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
2052 let result_ty = match ty::get(ctor_ty).sty {
2053 ty::ty_bare_fn(ref bft) => bft.sig.output,
2054 _ => ccx.sess().bug(
2055 format!("trans_enum_variant_or_tuple_like_struct: \
2056 unexpected ctor return type {}",
2057 ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
2060 let arena = TypedArena::new();
2061 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
2062 param_substs, None, &arena);
2063 let bcx = init_function(&fcx, false, result_ty);
2065 assert!(!fcx.needs_ret_allocas);
2067 let arg_tys = ty::ty_fn_args(ctor_ty);
2069 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
2071 if !type_is_zero_size(fcx.ccx, result_ty) {
2072 let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
2073 let repr = adt::represent_type(ccx, result_ty);
2074 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
2075 let lldestptr = adt::trans_field_ptr(bcx,
2080 arg_datum.store_to(bcx, lldestptr);
2082 adt::trans_set_discr(bcx, &*repr, dest, disr);
2085 finish_fn(&fcx, bcx, result_ty);
2088 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
2089 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
2091 let levels = ccx.tcx().node_lint_levels.borrow();
2092 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
2093 let lvlsrc = match levels.find(&(id, lint_id)) {
2094 None | Some(&(lint::Allow, _)) => return,
2095 Some(&lvlsrc) => lvlsrc,
2098 let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
2100 adt::General(_, ref variants, _) => {
2101 for var in variants.iter() {
2103 for field in var.fields.iter().skip(1) {
2104 // skip the discriminant
2105 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
2110 _ => { /* its size is either constant or unimportant */ }
2113 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
2114 |(l, s, li), (idx, &size)|
2117 } else if size > s {
2124 // we only warn if the largest variant is at least thrice as large as
2125 // the second-largest.
2126 if largest > slargest * 3 && slargest > 0 {
2127 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
2128 // pass for the latter already ran.
2129 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
2131 format!("enum variant is more than three times larger \
2132 ({} bytes) than the next largest (ignoring padding)",
2133 largest).as_slice());
2135 ccx.sess().span_note(enum_def.variants.get(largest_index).span,
2136 "this variant is the largest");
2140 pub struct TransItemVisitor<'a, 'tcx: 'a> {
2141 pub ccx: &'a CrateContext<'a, 'tcx>,
2144 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
2145 fn visit_item(&mut self, i: &ast::Item) {
2146 trans_item(self.ccx, i);
2150 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
2151 pub enum ValueOrigin {
2152 /// The LLVM `Value` is in this context because the corresponding item was
2153 /// assigned to the current compilation unit.
2154 OriginalTranslation,
2155 /// The `Value`'s corresponding item was assigned to some other compilation
2156 /// unit, but the `Value` was translated in this context anyway because the
2157 /// item is marked `#[inline]`.
2161 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
2162 /// If the `llval` is the direct translation of a specific Rust item, `id`
2163 /// should be set to the `NodeId` of that item. (This mapping should be
2164 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
2165 /// `None`.) `llval_origin` indicates whether `llval` is the translation of an
2166 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
2167 /// assigned to a different compilation unit.
2168 pub fn update_linkage(ccx: &CrateContext,
2170 id: Option<ast::NodeId>,
2171 llval_origin: ValueOrigin) {
2172 match llval_origin {
2174 // `llval` is a translation of an item defined in a separate
2175 // compilation unit. This only makes sense if there are at least
2176 // two compilation units.
2177 assert!(ccx.sess().opts.cg.codegen_units > 1);
2178 // `llval` is a copy of something defined elsewhere, so use
2179 // `AvailableExternallyLinkage` to avoid duplicating code in the
2181 llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
2184 OriginalTranslation => {},
2188 Some(id) if ccx.reachable().contains(&id) => {
2189 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2192 // `id` does not refer to an item in `ccx.reachable`.
2193 if ccx.sess().opts.cg.codegen_units > 1 {
2194 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2196 llvm::SetLinkage(llval, llvm::InternalLinkage);
2202 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
2203 let _icx = push_ctxt("trans_item");
2205 let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2208 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
2209 if !generics.is_type_parameterized() {
2210 let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
2211 // Ignore `trans_everywhere` for cross-crate inlined items
2212 // (`from_external`). `trans_item` will be called once for each
2213 // compilation unit that references the item, so it will still get
2214 // translated everywhere it's needed.
2215 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2216 let llfn = get_item_val(ccx, item.id);
2218 foreign::trans_rust_fn_with_foreign_abi(ccx,
2221 item.attrs.as_slice(),
2223 ¶m_substs::empty(),
2231 ¶m_substs::empty(),
2233 item.attrs.as_slice());
2238 if is_origin { OriginalTranslation } else { InlinedCopy });
2242 // Be sure to travel more than just one layer deep to catch nested
2243 // items in blocks and such.
2244 let mut v = TransItemVisitor{ ccx: ccx };
2245 v.visit_block(&**body);
2247 ast::ItemImpl(ref generics, _, _, ref impl_items) => {
2248 meth::trans_impl(ccx,
2250 impl_items.as_slice(),
2254 ast::ItemMod(ref m) => {
2255 trans_mod(&ccx.rotate(), m);
2257 ast::ItemEnum(ref enum_definition, _) => {
2258 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2260 ast::ItemStatic(_, m, ref expr) => {
2261 // Recurse on the expression to catch items in blocks
2262 let mut v = TransItemVisitor{ ccx: ccx };
2263 v.visit_expr(&**expr);
2265 let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
2266 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2267 consts::trans_const(ccx, m, item.id);
2269 let g = get_item_val(ccx, item.id);
2273 if is_origin { OriginalTranslation } else { InlinedCopy });
2276 // Do static_assert checking. It can't really be done much earlier
2277 // because we need to get the value of the bool out of LLVM
2278 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
2279 if m == ast::MutMutable {
2280 ccx.sess().span_fatal(expr.span,
2281 "cannot have static_assert on a mutable \
2285 let v = ccx.const_values().borrow().get_copy(&item.id);
2287 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2288 ccx.sess().span_fatal(expr.span, "static assertion failed");
2293 ast::ItemForeignMod(ref foreign_mod) => {
2294 foreign::trans_foreign_mod(ccx, foreign_mod);
2296 ast::ItemTrait(..) => {
2297 // Inside of this trait definition, we won't be actually translating any
2298 // functions, but the trait still needs to be walked. Otherwise default
2299 // methods with items will not get translated and will cause ICE's when
2300 // metadata time comes around.
2301 let mut v = TransItemVisitor{ ccx: ccx };
2302 visit::walk_item(&mut v, item);
2304 _ => {/* fall through */ }
2308 // Translate a module. Doing this amounts to translating the items in the
2309 // module; there ends up being no artifact (aside from linkage names) of
2310 // separate modules in the compiled program. That's because modules exist
2311 // only as a convenience for humans working with the code, to organize names
2312 // and control visibility.
2313 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2314 let _icx = push_ctxt("trans_mod");
2315 for item in m.items.iter() {
2316 trans_item(ccx, &**item);
2320 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
2322 ccx.item_symbols().borrow_mut().insert(node_id, sym);
2324 // The stack exhaustion lang item shouldn't have a split stack because
2325 // otherwise it would continue to be exhausted (bad), and both it and the
2326 // eh_personality functions need to be externally linkable.
2327 let def = ast_util::local_def(node_id);
2328 if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2329 unset_split_stack(llfn);
2330 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2332 if ccx.tcx().lang_items.eh_personality() == Some(def) {
2333 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2337 if is_entry_fn(ccx.sess(), node_id) {
2338 create_entry_wrapper(ccx, sp, llfn);
2342 fn register_fn(ccx: &CrateContext,
2345 node_id: ast::NodeId,
2348 match ty::get(node_type).sty {
2349 ty::ty_bare_fn(ref f) => {
2350 assert!(f.abi == Rust || f.abi == RustCall);
2352 _ => fail!("expected bare rust fn")
2355 let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
2356 finish_register_fn(ccx, sp, sym, node_id, llfn);
2360 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
2361 -> llvm::AttrBuilder {
2362 use middle::ty::{BrAnon, ReLateBound};
2364 let (fn_sig, abi, has_env) = match ty::get(fn_ty).sty {
2365 ty::ty_closure(ref f) => (f.sig.clone(), f.abi, true),
2366 ty::ty_bare_fn(ref f) => (f.sig.clone(), f.abi, false),
2367 ty::ty_unboxed_closure(closure_did, _) => {
2368 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
2369 let ref function_type = unboxed_closures.get(&closure_did)
2372 (function_type.sig.clone(), RustCall, true)
2374 _ => ccx.sess().bug("expected closure or function.")
2378 // Since index 0 is the return value of the llvm func, we start
2379 // at either 1 or 2 depending on whether there's an env slot or not
2380 let mut first_arg_offset = if has_env { 2 } else { 1 };
2381 let mut attrs = llvm::AttrBuilder::new();
2382 let ret_ty = fn_sig.output;
2384 // These have an odd calling convention, so we need to manually
2385 // unpack the input ty's
2386 let input_tys = match ty::get(fn_ty).sty {
2387 ty::ty_unboxed_closure(_, _) => {
2388 assert!(abi == RustCall);
2390 match ty::get(fn_sig.inputs[0]).sty {
2391 ty::ty_nil => Vec::new(),
2392 ty::ty_tup(ref inputs) => inputs.clone(),
2393 _ => ccx.sess().bug("expected tuple'd inputs")
2396 ty::ty_bare_fn(_) if abi == RustCall => {
2397 let inputs = vec![fn_sig.inputs[0]];
2399 match ty::get(fn_sig.inputs[1]).sty {
2400 ty::ty_nil => inputs,
2401 ty::ty_tup(ref t_in) => inputs.append(t_in.as_slice()),
2402 _ => ccx.sess().bug("expected tuple'd inputs")
2405 _ => fn_sig.inputs.clone()
2408 // A function pointer is called without the declaration
2409 // available, so we have to apply any attributes with ABI
2410 // implications directly to the call instruction. Right now,
2411 // the only attribute we need to worry about is `sret`.
2412 if type_of::return_uses_outptr(ccx, ret_ty) {
2413 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
2415 // The outptr can be noalias and nocapture because it's entirely
2416 // invisible to the program. We also know it's nonnull as well
2417 // as how many bytes we can dereference
2418 attrs.arg(1, llvm::StructRetAttribute)
2419 .arg(1, llvm::NoAliasAttribute)
2420 .arg(1, llvm::NoCaptureAttribute)
2421 .arg(1, llvm::DereferenceableAttribute(llret_sz));
2423 // Add one more since there's an outptr
2424 first_arg_offset += 1;
2426 // The `noalias` attribute on the return value is useful to a
2427 // function ptr caller.
2428 match ty::get(ret_ty).sty {
2429 // `~` pointer return values never alias because ownership
2431 ty::ty_uniq(it) if !ty::type_is_sized(ccx.tcx(), it) => {}
2433 attrs.ret(llvm::NoAliasAttribute);
2438 // We can also mark the return value as `dereferenceable` in certain cases
2439 match ty::get(ret_ty).sty {
2440 // These are not really pointers but pairs, (pointer, len)
2442 ty::ty_rptr(_, ty::mt { ty: it, .. }) if !ty::type_is_sized(ccx.tcx(), it) => {}
2443 ty::ty_uniq(inner) | ty::ty_rptr(_, ty::mt { ty: inner, .. }) => {
2444 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2445 attrs.ret(llvm::DereferenceableAttribute(llret_sz));
2450 match ty::get(ret_ty).sty {
2452 attrs.ret(llvm::ZExtAttribute);
2458 for (idx, &t) in input_tys.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2459 match ty::get(t).sty {
2460 // this needs to be first to prevent fat pointers from falling through
2461 _ if !type_is_immediate(ccx, t) => {
2462 let llarg_sz = llsize_of_real(ccx, type_of::type_of(ccx, t));
2464 // For non-immediate arguments the callee gets its own copy of
2465 // the value on the stack, so there are no aliases. It's also
2466 // program-invisible so can't possibly capture
2467 attrs.arg(idx, llvm::NoAliasAttribute)
2468 .arg(idx, llvm::NoCaptureAttribute)
2469 .arg(idx, llvm::DereferenceableAttribute(llarg_sz));
2473 attrs.arg(idx, llvm::ZExtAttribute);
2476 // `~` pointer parameters never alias because ownership is transferred
2477 ty::ty_uniq(inner) => {
2478 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2480 attrs.arg(idx, llvm::NoAliasAttribute)
2481 .arg(idx, llvm::DereferenceableAttribute(llsz));
2484 // The visit glue deals only with opaque pointers so we don't
2485 // actually know the concrete type of Self thus we don't know how
2486 // many bytes to mark as dereferenceable so instead we just mark
2487 // it as nonnull which still holds true
2488 ty::ty_rptr(b, ty::mt { ty: it, mutbl }) if match ty::get(it).sty {
2489 ty::ty_param(_) => true, _ => false
2490 } && mutbl == ast::MutMutable => {
2491 attrs.arg(idx, llvm::NoAliasAttribute)
2492 .arg(idx, llvm::NonNullAttribute);
2495 ReLateBound(_, BrAnon(_)) => {
2496 attrs.arg(idx, llvm::NoCaptureAttribute);
2502 // `&mut` pointer parameters never alias other parameters, or mutable global data
2504 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
2505 // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on
2506 // memory dependencies rather than pointer equality
2507 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable ||
2508 !ty::type_contents(ccx.tcx(), mt.ty).interior_unsafe() => {
2510 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2511 attrs.arg(idx, llvm::NoAliasAttribute)
2512 .arg(idx, llvm::DereferenceableAttribute(llsz));
2514 if mt.mutbl == ast::MutImmutable {
2515 attrs.arg(idx, llvm::ReadOnlyAttribute);
2519 ReLateBound(_, BrAnon(_)) => {
2520 attrs.arg(idx, llvm::NoCaptureAttribute);
2526 // When a reference in an argument has no named lifetime, it's impossible for that
2527 // reference to escape this function (returned or stored beyond the call by a closure).
2528 ty::ty_rptr(ReLateBound(_, BrAnon(_)), mt) => {
2529 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2530 attrs.arg(idx, llvm::NoCaptureAttribute)
2531 .arg(idx, llvm::DereferenceableAttribute(llsz));
2534 // & pointer parameters are also never null and we know exactly how
2535 // many bytes we can dereference
2536 ty::ty_rptr(_, mt) => {
2537 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2538 attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
2547 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2548 pub fn register_fn_llvmty(ccx: &CrateContext,
2551 node_id: ast::NodeId,
2553 llfty: Type) -> ValueRef {
2554 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2556 let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
2557 finish_register_fn(ccx, sp, sym, node_id, llfn);
2561 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2562 match *sess.entry_fn.borrow() {
2563 Some((entry_id, _)) => node_id == entry_id,
2568 // Create a _rust_main(args: ~[str]) function which will be called from the
2569 // runtime rust_start function
2570 pub fn create_entry_wrapper(ccx: &CrateContext,
2572 main_llfn: ValueRef) {
2573 let et = ccx.sess().entry_type.get().unwrap();
2575 config::EntryMain => {
2576 create_entry_fn(ccx, main_llfn, true);
2578 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2579 config::EntryNone => {} // Do nothing.
2582 fn create_entry_fn(ccx: &CrateContext,
2583 rust_main: ValueRef,
2584 use_start_lang_item: bool) {
2585 let llfty = Type::func([ccx.int_type(), Type::i8p(ccx).ptr_to()],
2588 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
2590 // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2591 // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2592 if ccx.sess().targ_cfg.os == OsWindows {
2593 unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2596 let llbb = "top".with_c_str(|buf| {
2598 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, buf)
2601 let bld = ccx.raw_builder();
2603 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2605 let (start_fn, args) = if use_start_lang_item {
2606 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2608 Err(s) => { ccx.sess().fatal(s.as_slice()); }
2610 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2611 get_item_val(ccx, start_def_id.node)
2613 let start_fn_type = csearch::get_type(ccx.tcx(),
2615 trans_external_path(ccx, start_def_id, start_fn_type)
2619 let opaque_rust_main = "rust_main".with_c_str(|buf| {
2620 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
2631 debug!("using user-defined start fn");
2633 get_param(llfn, 0 as c_uint),
2634 get_param(llfn, 1 as c_uint)
2640 let result = llvm::LLVMBuildCall(bld,
2643 args.len() as c_uint,
2646 llvm::LLVMBuildRet(bld, result);
2651 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2652 ty: ty::t, attrs: &[ast::Attribute]) -> String {
2653 match ccx.external_srcs().borrow().find(&id) {
2655 let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2656 debug!("found item {} in other crate...", sym);
2662 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2663 // Use provided name
2664 Some(name) => name.get().to_string(),
2666 _ => ccx.tcx().map.with_path(id, |mut path| {
2667 if attr::contains_name(attrs, "no_mangle") {
2669 path.last().unwrap().to_string()
2671 match weak_lang_items::link_name(attrs) {
2672 Some(name) => name.get().to_string(),
2674 // Usual name mangling
2675 mangle_exported_name(ccx, path, ty, id)
2683 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2684 debug!("get_item_val(id=`{:?}`)", id);
2686 match ccx.item_vals().borrow().find_copy(&id) {
2687 Some(v) => return v,
2691 let item = ccx.tcx().map.get(id);
2692 let val = match item {
2693 ast_map::NodeItem(i) => {
2694 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2695 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2697 let v = match i.node {
2698 ast::ItemStatic(_, mutbl, ref expr) => {
2699 // If this static came from an external crate, then
2700 // we need to get the symbol from csearch instead of
2701 // using the current crate's name/version
2702 // information in the hash of the symbol
2703 debug!("making {}", sym);
2704 let is_local = !ccx.external_srcs().borrow().contains_key(&id);
2706 // We need the translated value here, because for enums the
2707 // LLVM type is not fully determined by the Rust type.
2708 let (v, inlineable, _) = consts::const_expr(ccx, &**expr, is_local);
2709 ccx.const_values().borrow_mut().insert(id, v);
2710 let mut inlineable = inlineable;
2713 let llty = llvm::LLVMTypeOf(v);
2714 let g = sym.as_slice().with_c_str(|buf| {
2715 llvm::LLVMAddGlobal(ccx.llmod(), llty, buf)
2718 // Apply the `unnamed_addr` attribute if
2720 if !ast_util::static_has_significant_address(
2722 i.attrs.as_slice()) {
2723 llvm::SetUnnamedAddr(g, true);
2725 // This is a curious case where we must make
2726 // all of these statics inlineable. If a
2727 // global is not tagged as `#[inline(never)]`,
2728 // then LLVM won't coalesce globals unless they
2729 // have an internal linkage type. This means that
2730 // external crates cannot use this global.
2731 // This is a problem for things like inner
2732 // statics in generic functions, because the
2733 // function will be inlined into another
2734 // crate and then attempt to link to the
2735 // static in the original crate, only to
2736 // find that it's not there. On the other
2737 // side of inlining, the crates knows to
2738 // not declare this static as
2739 // available_externally (because it isn't)
2743 if attr::contains_name(i.attrs.as_slice(),
2745 llvm::set_thread_local(g, true);
2749 debug!("{} not inlined", sym);
2750 ccx.non_inlineable_statics().borrow_mut()
2754 ccx.item_symbols().borrow_mut().insert(i.id, sym);
2759 ast::ItemFn(_, _, abi, _, _) => {
2760 let llfn = if abi == Rust {
2761 register_fn(ccx, i.span, sym, i.id, ty)
2763 foreign::register_rust_fn_with_foreign_abi(ccx,
2768 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2772 _ => fail!("get_item_val: weird result in table")
2775 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2777 Some(sect) => unsafe {
2778 sect.get().with_c_str(|buf| {
2779 llvm::LLVMSetSection(v, buf);
2788 ast_map::NodeTraitItem(trait_method) => {
2789 debug!("get_item_val(): processing a NodeTraitItem");
2790 match *trait_method {
2791 ast::RequiredMethod(_) => {
2792 ccx.sess().bug("unexpected variant: required trait method in \
2795 ast::ProvidedMethod(ref m) => {
2796 register_method(ccx, id, &**m)
2801 ast_map::NodeImplItem(ii) => {
2803 ast::MethodImplItem(ref m) => register_method(ccx, id, &**m),
2807 ast_map::NodeForeignItem(ni) => {
2809 ast::ForeignItemFn(..) => {
2810 let abi = ccx.tcx().map.get_foreign_abi(id);
2811 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2812 let name = foreign::link_name(&*ni);
2813 foreign::register_foreign_item_fn(ccx, abi, ty,
2814 name.get().as_slice(),
2817 ast::ForeignItemStatic(..) => {
2818 foreign::register_static(ccx, &*ni)
2823 ast_map::NodeVariant(ref v) => {
2825 let args = match v.node.kind {
2826 ast::TupleVariantKind(ref args) => args,
2827 ast::StructVariantKind(_) => {
2828 fail!("struct variant kind unexpected in get_item_val")
2831 assert!(args.len() != 0u);
2832 let ty = ty::node_id_to_type(ccx.tcx(), id);
2833 let parent = ccx.tcx().map.get_parent(id);
2834 let enm = ccx.tcx().map.expect_item(parent);
2835 let sym = exported_name(ccx,
2838 enm.attrs.as_slice());
2840 llfn = match enm.node {
2841 ast::ItemEnum(_, _) => {
2842 register_fn(ccx, (*v).span, sym, id, ty)
2844 _ => fail!("NodeVariant, shouldn't happen")
2846 set_inline_hint(llfn);
2850 ast_map::NodeStructCtor(struct_def) => {
2851 // Only register the constructor if this is a tuple-like struct.
2852 let ctor_id = match struct_def.ctor_id {
2854 ccx.sess().bug("attempt to register a constructor of \
2855 a non-tuple-like struct")
2857 Some(ctor_id) => ctor_id,
2859 let parent = ccx.tcx().map.get_parent(id);
2860 let struct_item = ccx.tcx().map.expect_item(parent);
2861 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2862 let sym = exported_name(ccx,
2867 let llfn = register_fn(ccx, struct_item.span,
2869 set_inline_hint(llfn);
2874 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2875 variant).as_slice())
2879 // All LLVM globals and functions are initially created as external-linkage
2880 // declarations. If `trans_item`/`trans_fn` later turns the declaration
2881 // into a definition, it adjusts the linkage then (using `update_linkage`).
2883 // The exception is foreign items, which have their linkage set inside the
2884 // call to `foreign::register_*` above. We don't touch the linkage after
2885 // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2886 // other item translation functions do).
2888 ccx.item_vals().borrow_mut().insert(id, val);
2892 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2893 m: &ast::Method) -> ValueRef {
2894 let mty = ty::node_id_to_type(ccx.tcx(), id);
2896 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2898 let llfn = register_fn(ccx, m.span, sym, id, mty);
2899 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2903 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2905 return llvm::LLVMConstPtrToInt(v, ccx.int_type().to_ref());
2909 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2910 ie: encoder::EncodeInlinedItem<'a>)
2911 -> encoder::EncodeParams<'a, 'tcx> {
2912 encoder::EncodeParams {
2913 diag: cx.sess().diagnostic(),
2915 reexports2: cx.exp_map2(),
2916 item_symbols: cx.item_symbols(),
2917 non_inlineable_statics: cx.non_inlineable_statics(),
2918 link_meta: cx.link_meta(),
2919 cstore: &cx.sess().cstore,
2920 encode_inlined_item: ie,
2921 reachable: cx.reachable(),
2925 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2928 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2929 *ty != config::CrateTypeExecutable
2935 let encode_inlined_item: encoder::EncodeInlinedItem =
2936 |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii);
2938 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2939 let metadata = encoder::encode_metadata(encode_parms, krate);
2940 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2941 .append(match flate::deflate_bytes(metadata.as_slice()) {
2942 Some(compressed) => compressed,
2944 cx.sess().fatal("failed to compress metadata")
2947 let llmeta = C_bytes_in_context(cx.metadata_llcx(), compressed.as_slice());
2948 let llconst = C_struct_in_context(cx.metadata_llcx(), [llmeta], false);
2949 let name = format!("rust_metadata_{}_{}",
2950 cx.link_meta().crate_name,
2951 cx.link_meta().crate_hash);
2952 let llglobal = name.with_c_str(|buf| {
2954 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf)
2958 llvm::LLVMSetInitializer(llglobal, llconst);
2959 let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2960 name.unwrap_or("rust_metadata").with_c_str(|buf| {
2961 llvm::LLVMSetSection(llglobal, buf)
2967 /// Find any symbols that are defined in one compilation unit, but not declared
2968 /// in any other compilation unit. Give these symbols internal linkage.
2969 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
2970 use std::c_str::CString;
2973 let mut declared = HashSet::new();
2975 let iter_globals = |llmod| {
2977 cur: llvm::LLVMGetFirstGlobal(llmod),
2978 step: llvm::LLVMGetNextGlobal,
2982 let iter_functions = |llmod| {
2984 cur: llvm::LLVMGetFirstFunction(llmod),
2985 step: llvm::LLVMGetNextFunction,
2989 // Collect all external declarations in all compilation units.
2990 for ccx in cx.iter() {
2991 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2992 let linkage = llvm::LLVMGetLinkage(val);
2993 // We only care about external declarations (not definitions)
2994 // and available_externally definitions.
2995 if !(linkage == llvm::ExternalLinkage as c_uint &&
2996 llvm::LLVMIsDeclaration(val) != 0) &&
2997 !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
3001 let name = CString::new(llvm::LLVMGetValueName(val), false);
3002 declared.insert(name);
3006 // Examine each external definition. If the definition is not used in
3007 // any other compilation unit, and is not reachable from other crates,
3008 // then give it internal linkage.
3009 for ccx in cx.iter() {
3010 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
3011 // We only care about external definitions.
3012 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
3013 llvm::LLVMIsDeclaration(val) == 0) {
3017 let name = CString::new(llvm::LLVMGetValueName(val), false);
3018 if !declared.contains(&name) &&
3019 !reachable.contains_equiv(&name.as_str().unwrap()) {
3020 llvm::SetLinkage(val, llvm::InternalLinkage);
3029 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
3032 impl Iterator<ValueRef> for ValueIter {
3033 fn next(&mut self) -> Option<ValueRef> {
3036 self.cur = unsafe { (self.step)(old) };
3045 pub fn trans_crate<'tcx>(analysis: CrateAnalysis<'tcx>)
3046 -> (ty::ctxt<'tcx>, CrateTranslation) {
3047 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
3048 let krate = tcx.map.krate();
3050 // Before we touch LLVM, make sure that multithreading is enabled.
3052 use std::sync::{Once, ONCE_INIT};
3053 static mut INIT: Once = ONCE_INIT;
3054 static mut POISONED: bool = false;
3056 if llvm::LLVMStartMultithreaded() != 1 {
3057 // use an extra bool to make sure that all future usage of LLVM
3058 // cannot proceed despite the Once not running more than once.
3064 tcx.sess.bug("couldn't enable multi-threaded LLVM");
3068 let link_meta = link::build_link_meta(&tcx.sess, krate, name);
3070 let codegen_units = tcx.sess.opts.cg.codegen_units;
3071 let shared_ccx = SharedCrateContext::new(link_meta.crate_name.as_slice(),
3080 let ccx = shared_ccx.get_ccx(0);
3082 // First, verify intrinsics.
3083 intrinsic::check_intrinsics(&ccx);
3085 // Next, translate the module.
3087 let _icx = push_ctxt("text");
3088 trans_mod(&ccx, &krate.module);
3092 for ccx in shared_ccx.iter() {
3093 glue::emit_tydescs(&ccx);
3094 if ccx.sess().opts.debuginfo != NoDebugInfo {
3095 debuginfo::finalize(&ccx);
3099 // Translate the metadata.
3100 let metadata = write_metadata(&shared_ccx, krate);
3102 if shared_ccx.sess().trans_stats() {
3103 let stats = shared_ccx.stats();
3104 println!("--- trans stats ---");
3105 println!("n_static_tydescs: {}", stats.n_static_tydescs.get());
3106 println!("n_glues_created: {}", stats.n_glues_created.get());
3107 println!("n_null_glues: {}", stats.n_null_glues.get());
3108 println!("n_real_glues: {}", stats.n_real_glues.get());
3110 println!("n_fns: {}", stats.n_fns.get());
3111 println!("n_monos: {}", stats.n_monos.get());
3112 println!("n_inlines: {}", stats.n_inlines.get());
3113 println!("n_closures: {}", stats.n_closures.get());
3114 println!("fn stats:");
3115 stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
3116 insns_b.cmp(&insns_a)
3118 for tuple in stats.fn_stats.borrow().iter() {
3120 (ref name, ms, insns) => {
3121 println!("{} insns, {} ms, {}", insns, ms, *name);
3126 if shared_ccx.sess().count_llvm_insns() {
3127 for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
3128 println!("{:7u} {}", *v, *k);
3132 let modules = shared_ccx.iter()
3133 .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
3136 let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
3137 shared_ccx.item_symbols().borrow().find(id).map(|s| s.to_string())
3140 // For the purposes of LTO, we add to the reachable set all of the upstream
3141 // reachable extern fns. These functions are all part of the public ABI of
3142 // the final product, so LTO needs to preserve them.
3143 shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
3144 let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
3145 reachable.extend(syms.move_iter().map(|did| {
3146 csearch::get_symbol(&shared_ccx.sess().cstore, did)
3150 // Make sure that some other crucial symbols are not eliminated from the
3151 // module. This includes the main function, the crate map (used for debug
3152 // log settings and I/O), and finally the curious rust_stack_exhausted
3153 // symbol. This symbol is required for use by the libmorestack library that
3154 // we link in, so we must ensure that this symbol is not internalized (if
3155 // defined in the crate).
3156 reachable.push("main".to_string());
3157 reachable.push("rust_stack_exhausted".to_string());
3159 // referenced from .eh_frame section on some platforms
3160 reachable.push("rust_eh_personality".to_string());
3161 // referenced from rt/rust_try.ll
3162 reachable.push("rust_eh_personality_catch".to_string());
3164 if codegen_units > 1 {
3165 internalize_symbols(&shared_ccx, &reachable.iter().map(|x| x.clone()).collect());
3168 let metadata_module = ModuleTranslation {
3169 llcx: shared_ccx.metadata_llcx(),
3170 llmod: shared_ccx.metadata_llmod(),
3172 let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
3173 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
3175 let translation = CrateTranslation {
3177 metadata_module: metadata_module,
3180 reachable: reachable,
3181 crate_formats: formats,
3182 no_builtins: no_builtins,
3185 (shared_ccx.take_tcx(), translation)