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 {
1328 impl Visitor<bool> for CheckForNestedReturnsVisitor {
1329 fn visit_expr(&mut self, e: &ast::Expr, in_return: bool) {
1331 ast::ExprRet(..) if in_return => {
1335 ast::ExprRet(..) => visit::walk_expr(self, e, true),
1336 _ => visit::walk_expr(self, e, in_return)
1341 fn has_nested_returns(tcx: &ty::ctxt, id: ast::NodeId) -> bool {
1342 match tcx.map.find(id) {
1343 Some(ast_map::NodeItem(i)) => {
1345 ast::ItemFn(_, _, _, _, blk) => {
1346 let mut explicit = CheckForNestedReturnsVisitor { found: false };
1347 let mut implicit = CheckForNestedReturnsVisitor { found: false };
1348 visit::walk_item(&mut explicit, &*i, false);
1349 visit::walk_expr_opt(&mut implicit, blk.expr, true);
1350 explicit.found || implicit.found
1352 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1355 Some(ast_map::NodeTraitItem(trait_method)) => {
1356 match *trait_method {
1357 ast::ProvidedMethod(m) => {
1359 ast::MethDecl(_, _, _, _, _, _, blk, _) => {
1360 let mut explicit = CheckForNestedReturnsVisitor { found: false };
1361 let mut implicit = CheckForNestedReturnsVisitor { found: false };
1362 visit::walk_method_helper(&mut explicit, &*m, false);
1363 visit::walk_expr_opt(&mut implicit, blk.expr, true);
1364 explicit.found || implicit.found
1366 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1369 ast::RequiredMethod(_) => {
1370 tcx.sess.bug("unexpected variant: required trait method \
1371 in has_nested_returns")
1375 Some(ast_map::NodeImplItem(ref ii)) => {
1377 ast::MethodImplItem(ref m) => {
1379 ast::MethDecl(_, _, _, _, _, _, blk, _) => {
1380 let mut explicit = CheckForNestedReturnsVisitor {
1383 let mut implicit = CheckForNestedReturnsVisitor {
1386 visit::walk_method_helper(&mut explicit,
1389 visit::walk_expr_opt(&mut implicit,
1392 explicit.found || implicit.found
1394 ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1399 Some(ast_map::NodeExpr(e)) => {
1401 ast::ExprFnBlock(_, _, blk) |
1402 ast::ExprProc(_, blk) |
1403 ast::ExprUnboxedFn(_, _, _, blk) => {
1404 let mut explicit = CheckForNestedReturnsVisitor { found: false };
1405 let mut implicit = CheckForNestedReturnsVisitor { found: false };
1406 visit::walk_expr(&mut explicit, &*e, false);
1407 visit::walk_expr_opt(&mut implicit, blk.expr, true);
1408 explicit.found || implicit.found
1410 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1414 Some(ast_map::NodeVariant(..)) | Some(ast_map::NodeStructCtor(..)) => false,
1417 None if id == ast::DUMMY_NODE_ID => false,
1419 _ => tcx.sess.bug(format!("unexpected variant in has_nested_returns: {}",
1420 tcx.map.path_to_string(id)).as_slice())
1424 // NB: must keep 4 fns in sync:
1427 // - create_datums_for_fn_args.
1431 // Be warned! You must call `init_function` before doing anything with the
1432 // returned function context.
1433 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1438 param_substs: &'a param_substs,
1440 block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1441 -> FunctionContext<'a, 'tcx> {
1442 param_substs.validate();
1444 debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1448 ccx.tcx().map.path_to_string(id).to_string()
1450 id, param_substs.repr(ccx.tcx()));
1452 let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1453 let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1454 let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1455 let nested_returns = has_nested_returns(ccx.tcx(), id);
1457 let mut fcx = FunctionContext {
1460 llretslotptr: Cell::new(None),
1461 alloca_insert_pt: Cell::new(None),
1462 llreturn: Cell::new(None),
1463 needs_ret_allocas: nested_returns,
1464 personality: Cell::new(None),
1465 caller_expects_out_pointer: uses_outptr,
1466 llargs: RefCell::new(NodeMap::new()),
1467 lllocals: RefCell::new(NodeMap::new()),
1468 llupvars: RefCell::new(NodeMap::new()),
1470 param_substs: param_substs,
1472 block_arena: block_arena,
1474 debug_context: debug_context,
1475 scopes: RefCell::new(Vec::new())
1479 fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1485 /// Performs setup on a newly created function, creating the entry scope block
1486 /// and allocating space for the return pointer.
1487 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1489 output_type: ty::t) -> Block<'a, 'tcx> {
1490 let entry_bcx = fcx.new_temp_block("entry-block");
1492 // Use a dummy instruction as the insertion point for all allocas.
1493 // This is later removed in FunctionContext::cleanup.
1494 fcx.alloca_insert_pt.set(Some(unsafe {
1495 Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1496 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1499 // This shouldn't need to recompute the return type,
1500 // as new_fn_ctxt did it already.
1501 let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1503 if !return_type_is_void(fcx.ccx, substd_output_type) {
1504 // If the function returns nil/bot, there is no real return
1505 // value, so do not set `llretslotptr`.
1506 if !skip_retptr || fcx.caller_expects_out_pointer {
1507 // Otherwise, we normally allocate the llretslotptr, unless we
1508 // have been instructed to skip it for immediate return
1510 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1517 // NB: must keep 4 fns in sync:
1520 // - create_datums_for_fn_args.
1524 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1525 use middle::trans::datum::{ByRef, ByValue};
1528 mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1532 // work around bizarre resolve errors
1533 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1534 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1536 // create_datums_for_fn_args: creates rvalue datums for each of the
1537 // incoming function arguments. These will later be stored into
1538 // appropriate lvalue datums.
1539 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1541 -> Vec<RvalueDatum> {
1542 let _icx = push_ctxt("create_datums_for_fn_args");
1544 // Return an array wrapping the ValueRefs that we get from `get_param` for
1545 // each argument into datums.
1546 arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1547 let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1548 datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1552 /// Creates rvalue datums for each of the incoming function arguments and
1553 /// tuples the arguments. These will later be stored into appropriate lvalue
1556 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1557 fn create_datums_for_fn_args_under_call_abi(
1559 arg_scope: cleanup::CustomScopeIndex,
1561 -> Vec<RvalueDatum> {
1562 let mut result = Vec::new();
1563 for (i, &arg_ty) in arg_tys.iter().enumerate() {
1564 if i < arg_tys.len() - 1 {
1565 // Regular argument.
1566 let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1567 result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1572 // This is the last argument. Tuple it.
1573 match ty::get(arg_ty).sty {
1574 ty::ty_tup(ref tupled_arg_tys) => {
1575 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1578 datum::lvalue_scratch_datum(bcx,
1582 tuple_args_scope_id,
1587 for (j, &tupled_arg_ty) in
1588 tupled_arg_tys.iter().enumerate() {
1590 get_param(bcx.fcx.llfn,
1591 bcx.fcx.arg_pos(i + j) as c_uint);
1592 let lldest = GEPi(bcx, llval, [0, j]);
1593 let datum = datum::Datum::new(
1596 arg_kind(bcx.fcx, tupled_arg_ty));
1597 bcx = datum.store_to(bcx, lldest);
1601 let tuple = unpack_datum!(bcx,
1602 tuple.to_expr_datum()
1603 .to_rvalue_datum(bcx,
1608 let mode = datum::Rvalue::new(datum::ByValue);
1609 result.push(datum::Datum::new(C_nil(bcx.ccx()),
1614 bcx.tcx().sess.bug("last argument of a function with \
1615 `rust-call` ABI isn't a tuple?!")
1624 fn copy_args_to_allocas<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1625 arg_scope: cleanup::CustomScopeIndex,
1626 bcx: Block<'blk, 'tcx>,
1628 arg_datums: Vec<RvalueDatum> )
1629 -> Block<'blk, 'tcx> {
1630 debug!("copy_args_to_allocas");
1632 let _icx = push_ctxt("copy_args_to_allocas");
1635 let arg_scope_id = cleanup::CustomScope(arg_scope);
1637 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1638 // For certain mode/type combinations, the raw llarg values are passed
1639 // by value. However, within the fn body itself, we want to always
1640 // have all locals and arguments be by-ref so that we can cancel the
1641 // cleanup and for better interaction with LLVM's debug info. So, if
1642 // the argument would be passed by value, we store it into an alloca.
1643 // This alloca should be optimized away by LLVM's mem-to-reg pass in
1644 // the event it's not truly needed.
1646 bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1648 if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1649 debuginfo::create_argument_metadata(bcx, &args[i]);
1656 fn copy_unboxed_closure_args_to_allocas<'blk, 'tcx>(
1657 mut bcx: Block<'blk, 'tcx>,
1658 arg_scope: cleanup::CustomScopeIndex,
1660 arg_datums: Vec<RvalueDatum>,
1661 monomorphized_arg_types: &[ty::t])
1662 -> Block<'blk, 'tcx> {
1663 let _icx = push_ctxt("copy_unboxed_closure_args_to_allocas");
1664 let arg_scope_id = cleanup::CustomScope(arg_scope);
1666 assert_eq!(arg_datums.len(), 1);
1668 let arg_datum = arg_datums.move_iter().next().unwrap();
1670 // Untuple the rest of the arguments.
1673 arg_datum.to_lvalue_datum_in_scope(bcx,
1676 let empty = Vec::new();
1677 let untupled_arg_types = match ty::get(monomorphized_arg_types[0]).sty {
1678 ty::ty_tup(ref types) => types.as_slice(),
1679 ty::ty_nil => empty.as_slice(),
1681 bcx.tcx().sess.span_bug(args[0].pat.span,
1682 "first arg to `rust-call` ABI function \
1686 for j in range(0, args.len()) {
1687 let tuple_element_type = untupled_arg_types[j];
1688 let tuple_element_datum =
1689 tuple_datum.get_element(bcx,
1691 |llval| GEPi(bcx, llval, [0, j]));
1692 let tuple_element_datum = tuple_element_datum.to_expr_datum();
1693 let tuple_element_datum =
1695 tuple_element_datum.to_rvalue_datum(bcx,
1697 bcx = _match::store_arg(bcx,
1699 tuple_element_datum,
1702 if bcx.fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1703 debuginfo::create_argument_metadata(bcx, &args[j]);
1710 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1711 // and builds the return block.
1712 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1713 last_bcx: Block<'blk, 'tcx>,
1715 let _icx = push_ctxt("finish_fn");
1717 // This shouldn't need to recompute the return type,
1718 // as new_fn_ctxt did it already.
1719 let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1721 let ret_cx = match fcx.llreturn.get() {
1723 if !last_bcx.terminated.get() {
1724 Br(last_bcx, llreturn);
1726 raw_block(fcx, false, llreturn)
1730 build_return_block(fcx, ret_cx, substd_retty);
1731 debuginfo::clear_source_location(fcx);
1735 // Builds the return block for a function.
1736 pub fn build_return_block(fcx: &FunctionContext, ret_cx: Block, retty: ty::t) {
1737 if fcx.llretslotptr.get().is_none() ||
1738 (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1739 return RetVoid(ret_cx);
1742 let retslot = if fcx.needs_ret_allocas {
1743 Load(ret_cx, fcx.llretslotptr.get().unwrap())
1745 fcx.llretslotptr.get().unwrap()
1747 let retptr = Value(retslot);
1748 match retptr.get_dominating_store(ret_cx) {
1749 // If there's only a single store to the ret slot, we can directly return
1750 // the value that was stored and omit the store and the alloca
1752 let retval = s.get_operand(0).unwrap().get();
1753 s.erase_from_parent();
1755 if retptr.has_no_uses() {
1756 retptr.erase_from_parent();
1759 let retval = if ty::type_is_bool(retty) {
1760 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1765 if fcx.caller_expects_out_pointer {
1766 store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1767 return RetVoid(ret_cx);
1769 return Ret(ret_cx, retval);
1772 // Otherwise, copy the return value to the ret slot
1774 if fcx.caller_expects_out_pointer {
1775 memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1776 return RetVoid(ret_cx);
1778 return Ret(ret_cx, load_ty(ret_cx, retslot, retty));
1784 #[deriving(Clone, Eq, PartialEq)]
1785 pub enum IsUnboxedClosureFlag {
1790 // trans_closure: Builds an LLVM function out of a source function.
1791 // If the function closes over its environment a closure will be
1793 pub fn trans_closure(ccx: &CrateContext,
1797 param_substs: ¶m_substs,
1799 _attributes: &[ast::Attribute],
1800 arg_types: Vec<ty::t>,
1804 is_unboxed_closure: IsUnboxedClosureFlag,
1805 maybe_load_env: <'blk, 'tcx> |Block<'blk, 'tcx>, ScopeId|
1806 -> Block<'blk, 'tcx>) {
1807 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1809 let _icx = push_ctxt("trans_closure");
1810 set_uwtable(llfndecl);
1812 debug!("trans_closure(..., param_substs={})",
1813 param_substs.repr(ccx.tcx()));
1815 let arena = TypedArena::new();
1816 let fcx = new_fn_ctxt(ccx,
1824 let mut bcx = init_function(&fcx, false, output_type);
1826 // cleanup scope for the incoming arguments
1827 let arg_scope = fcx.push_custom_cleanup_scope();
1829 let block_ty = node_id_type(bcx, body.id);
1831 // Set up arguments to the function.
1832 let monomorphized_arg_types =
1834 .map(|at| monomorphize_type(bcx, *at))
1835 .collect::<Vec<_>>();
1836 for monomorphized_arg_type in monomorphized_arg_types.iter() {
1837 debug!("trans_closure: monomorphized_arg_type: {}",
1838 ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1840 debug!("trans_closure: function lltype: {}",
1841 bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1843 let arg_datums = if abi != RustCall {
1844 create_datums_for_fn_args(&fcx,
1845 monomorphized_arg_types.as_slice())
1847 create_datums_for_fn_args_under_call_abi(
1850 monomorphized_arg_types.as_slice())
1853 bcx = match is_unboxed_closure {
1854 NotUnboxedClosure => {
1855 copy_args_to_allocas(&fcx,
1858 decl.inputs.as_slice(),
1861 IsUnboxedClosure => {
1862 copy_unboxed_closure_args_to_allocas(
1865 decl.inputs.as_slice(),
1867 monomorphized_arg_types.as_slice())
1871 bcx = maybe_load_env(bcx, cleanup::CustomScope(arg_scope));
1873 // Up until here, IR instructions for this function have explicitly not been annotated with
1874 // source code location, so we don't step into call setup code. From here on, source location
1875 // emitting should be enabled.
1876 debuginfo::start_emitting_source_locations(&fcx);
1878 let dest = match fcx.llretslotptr.get() {
1879 Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, block_ty, "iret_slot")),
1881 assert!(type_is_zero_size(bcx.ccx(), block_ty));
1886 // This call to trans_block is the place where we bridge between
1887 // translation calls that don't have a return value (trans_crate,
1888 // trans_mod, trans_item, et cetera) and those that do
1889 // (trans_block, trans_expr, et cetera).
1890 bcx = controlflow::trans_block(bcx, body, dest);
1893 expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1894 Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1899 match fcx.llreturn.get() {
1901 Br(bcx, fcx.return_exit_block());
1902 fcx.pop_custom_cleanup_scope(arg_scope);
1905 // Microoptimization writ large: avoid creating a separate
1906 // llreturn basic block
1907 bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1911 // Put return block after all other blocks.
1912 // This somewhat improves single-stepping experience in debugger.
1914 let llreturn = fcx.llreturn.get();
1915 for &llreturn in llreturn.iter() {
1916 llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1920 // Insert the mandatory first few basic blocks before lltop.
1921 finish_fn(&fcx, bcx, output_type);
1924 // trans_fn: creates an LLVM function corresponding to a source language
1926 pub fn trans_fn(ccx: &CrateContext,
1930 param_substs: ¶m_substs,
1932 attrs: &[ast::Attribute]) {
1933 let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1934 debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1935 let _icx = push_ctxt("trans_fn");
1936 let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1937 let arg_types = ty::ty_fn_args(fn_ty);
1938 let output_type = ty::ty_fn_ret(fn_ty);
1939 let abi = ty::ty_fn_abi(fn_ty);
1955 pub fn trans_enum_variant(ccx: &CrateContext,
1956 _enum_id: ast::NodeId,
1957 variant: &ast::Variant,
1958 _args: &[ast::VariantArg],
1960 param_substs: ¶m_substs,
1961 llfndecl: ValueRef) {
1962 let _icx = push_ctxt("trans_enum_variant");
1964 trans_enum_variant_or_tuple_like_struct(
1972 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1975 args: callee::CallArgs,
1976 dest: expr::Dest) -> Result<'blk, 'tcx> {
1978 let ccx = bcx.fcx.ccx;
1979 let tcx = ccx.tcx();
1981 let result_ty = match ty::get(ctor_ty).sty {
1982 ty::ty_bare_fn(ref bft) => bft.sig.output,
1983 _ => ccx.sess().bug(
1984 format!("trans_enum_variant_constructor: \
1985 unexpected ctor return type {}",
1986 ctor_ty.repr(tcx)).as_slice())
1989 // Get location to store the result. If the user does not care about
1990 // the result, just make a stack slot
1991 let llresult = match dest {
1992 expr::SaveIn(d) => d,
1994 if !type_is_zero_size(ccx, result_ty) {
1995 alloc_ty(bcx, result_ty, "constructor_result")
1997 C_undef(type_of::type_of(ccx, result_ty))
2002 if !type_is_zero_size(ccx, result_ty) {
2004 callee::ArgExprs(exprs) => {
2005 let fields = exprs.iter().map(|x| *x).enumerate().collect::<Vec<_>>();
2006 bcx = expr::trans_adt(bcx, result_ty, disr, fields.as_slice(),
2007 None, expr::SaveIn(llresult));
2009 _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
2013 // If the caller doesn't care about the result
2014 // drop the temporary we made
2015 let bcx = match dest {
2016 expr::SaveIn(_) => bcx,
2017 expr::Ignore => glue::drop_ty(bcx, llresult, result_ty)
2020 Result::new(bcx, llresult)
2023 pub fn trans_tuple_struct(ccx: &CrateContext,
2024 _fields: &[ast::StructField],
2025 ctor_id: ast::NodeId,
2026 param_substs: ¶m_substs,
2027 llfndecl: ValueRef) {
2028 let _icx = push_ctxt("trans_tuple_struct");
2030 trans_enum_variant_or_tuple_like_struct(
2038 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
2039 ctor_id: ast::NodeId,
2041 param_substs: ¶m_substs,
2042 llfndecl: ValueRef) {
2043 let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2044 let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
2046 let result_ty = match ty::get(ctor_ty).sty {
2047 ty::ty_bare_fn(ref bft) => bft.sig.output,
2048 _ => ccx.sess().bug(
2049 format!("trans_enum_variant_or_tuple_like_struct: \
2050 unexpected ctor return type {}",
2051 ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
2054 let arena = TypedArena::new();
2055 let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
2056 param_substs, None, &arena);
2057 let bcx = init_function(&fcx, false, result_ty);
2059 assert!(!fcx.needs_ret_allocas);
2061 let arg_tys = ty::ty_fn_args(ctor_ty);
2063 let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
2065 if !type_is_zero_size(fcx.ccx, result_ty) {
2066 let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
2067 let repr = adt::represent_type(ccx, result_ty);
2068 for (i, arg_datum) in arg_datums.move_iter().enumerate() {
2069 let lldestptr = adt::trans_field_ptr(bcx,
2074 arg_datum.store_to(bcx, lldestptr);
2076 adt::trans_set_discr(bcx, &*repr, dest, disr);
2079 finish_fn(&fcx, bcx, result_ty);
2082 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
2083 let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
2085 let levels = ccx.tcx().node_lint_levels.borrow();
2086 let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
2087 let lvlsrc = match levels.find(&(id, lint_id)) {
2088 None | Some(&(lint::Allow, _)) => return,
2089 Some(&lvlsrc) => lvlsrc,
2092 let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
2094 adt::General(_, ref variants, _) => {
2095 for var in variants.iter() {
2097 for field in var.fields.iter().skip(1) {
2098 // skip the discriminant
2099 size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
2104 _ => { /* its size is either constant or unimportant */ }
2107 let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
2108 |(l, s, li), (idx, &size)|
2111 } else if size > s {
2118 // we only warn if the largest variant is at least thrice as large as
2119 // the second-largest.
2120 if largest > slargest * 3 && slargest > 0 {
2121 // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
2122 // pass for the latter already ran.
2123 lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
2125 format!("enum variant is more than three times larger \
2126 ({} bytes) than the next largest (ignoring padding)",
2127 largest).as_slice());
2129 ccx.sess().span_note(enum_def.variants.get(largest_index).span,
2130 "this variant is the largest");
2134 pub struct TransItemVisitor<'a, 'tcx: 'a> {
2135 pub ccx: &'a CrateContext<'a, 'tcx>,
2138 impl<'a, 'tcx> Visitor<()> for TransItemVisitor<'a, 'tcx> {
2139 fn visit_item(&mut self, i: &ast::Item, _:()) {
2140 trans_item(self.ccx, i);
2144 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
2145 pub enum ValueOrigin {
2146 /// The LLVM `Value` is in this context because the corresponding item was
2147 /// assigned to the current compilation unit.
2148 OriginalTranslation,
2149 /// The `Value`'s corresponding item was assigned to some other compilation
2150 /// unit, but the `Value` was translated in this context anyway because the
2151 /// item is marked `#[inline]`.
2155 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
2156 /// If the `llval` is the direct translation of a specific Rust item, `id`
2157 /// should be set to the `NodeId` of that item. (This mapping should be
2158 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
2159 /// `None`.) `llval_origin` indicates whether `llval` is the translation of an
2160 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
2161 /// assigned to a different compilation unit.
2162 pub fn update_linkage(ccx: &CrateContext,
2164 id: Option<ast::NodeId>,
2165 llval_origin: ValueOrigin) {
2166 match llval_origin {
2168 // `llval` is a translation of an item defined in a separate
2169 // compilation unit. This only makes sense if there are at least
2170 // two compilation units.
2171 assert!(ccx.sess().opts.cg.codegen_units > 1);
2172 // `llval` is a copy of something defined elsewhere, so use
2173 // `AvailableExternallyLinkage` to avoid duplicating code in the
2175 llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
2178 OriginalTranslation => {},
2182 Some(id) if ccx.reachable().contains(&id) => {
2183 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2186 // `id` does not refer to an item in `ccx.reachable`.
2187 if ccx.sess().opts.cg.codegen_units > 1 {
2188 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2190 llvm::SetLinkage(llval, llvm::InternalLinkage);
2196 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
2197 let _icx = push_ctxt("trans_item");
2199 let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2202 ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
2203 if !generics.is_type_parameterized() {
2204 let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
2205 // Ignore `trans_everywhere` for cross-crate inlined items
2206 // (`from_external`). `trans_item` will be called once for each
2207 // compilation unit that references the item, so it will still get
2208 // translated everywhere it's needed.
2209 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2210 let llfn = get_item_val(ccx, item.id);
2212 foreign::trans_rust_fn_with_foreign_abi(ccx,
2215 item.attrs.as_slice(),
2217 ¶m_substs::empty(),
2225 ¶m_substs::empty(),
2227 item.attrs.as_slice());
2232 if is_origin { OriginalTranslation } else { InlinedCopy });
2236 // Be sure to travel more than just one layer deep to catch nested
2237 // items in blocks and such.
2238 let mut v = TransItemVisitor{ ccx: ccx };
2239 v.visit_block(&**body, ());
2241 ast::ItemImpl(ref generics, _, _, ref impl_items) => {
2242 meth::trans_impl(ccx,
2244 impl_items.as_slice(),
2248 ast::ItemMod(ref m) => {
2249 trans_mod(&ccx.rotate(), m);
2251 ast::ItemEnum(ref enum_definition, _) => {
2252 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2254 ast::ItemStatic(_, m, ref expr) => {
2255 // Recurse on the expression to catch items in blocks
2256 let mut v = TransItemVisitor{ ccx: ccx };
2257 v.visit_expr(&**expr, ());
2259 let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
2260 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2261 consts::trans_const(ccx, m, item.id);
2263 let g = get_item_val(ccx, item.id);
2267 if is_origin { OriginalTranslation } else { InlinedCopy });
2270 // Do static_assert checking. It can't really be done much earlier
2271 // because we need to get the value of the bool out of LLVM
2272 if attr::contains_name(item.attrs.as_slice(), "static_assert") {
2273 if m == ast::MutMutable {
2274 ccx.sess().span_fatal(expr.span,
2275 "cannot have static_assert on a mutable \
2279 let v = ccx.const_values().borrow().get_copy(&item.id);
2281 if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2282 ccx.sess().span_fatal(expr.span, "static assertion failed");
2287 ast::ItemForeignMod(ref foreign_mod) => {
2288 foreign::trans_foreign_mod(ccx, foreign_mod);
2290 ast::ItemTrait(..) => {
2291 // Inside of this trait definition, we won't be actually translating any
2292 // functions, but the trait still needs to be walked. Otherwise default
2293 // methods with items will not get translated and will cause ICE's when
2294 // metadata time comes around.
2295 let mut v = TransItemVisitor{ ccx: ccx };
2296 visit::walk_item(&mut v, item, ());
2298 _ => {/* fall through */ }
2302 // Translate a module. Doing this amounts to translating the items in the
2303 // module; there ends up being no artifact (aside from linkage names) of
2304 // separate modules in the compiled program. That's because modules exist
2305 // only as a convenience for humans working with the code, to organize names
2306 // and control visibility.
2307 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2308 let _icx = push_ctxt("trans_mod");
2309 for item in m.items.iter() {
2310 trans_item(ccx, &**item);
2314 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
2316 ccx.item_symbols().borrow_mut().insert(node_id, sym);
2318 // The stack exhaustion lang item shouldn't have a split stack because
2319 // otherwise it would continue to be exhausted (bad), and both it and the
2320 // eh_personality functions need to be externally linkable.
2321 let def = ast_util::local_def(node_id);
2322 if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2323 unset_split_stack(llfn);
2324 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2326 if ccx.tcx().lang_items.eh_personality() == Some(def) {
2327 llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2331 if is_entry_fn(ccx.sess(), node_id) {
2332 create_entry_wrapper(ccx, sp, llfn);
2336 fn register_fn(ccx: &CrateContext,
2339 node_id: ast::NodeId,
2342 match ty::get(node_type).sty {
2343 ty::ty_bare_fn(ref f) => {
2344 assert!(f.abi == Rust || f.abi == RustCall);
2346 _ => fail!("expected bare rust fn")
2349 let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
2350 finish_register_fn(ccx, sp, sym, node_id, llfn);
2354 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
2355 -> llvm::AttrBuilder {
2356 use middle::ty::{BrAnon, ReLateBound};
2358 let (fn_sig, abi, has_env) = match ty::get(fn_ty).sty {
2359 ty::ty_closure(ref f) => (f.sig.clone(), f.abi, true),
2360 ty::ty_bare_fn(ref f) => (f.sig.clone(), f.abi, false),
2361 ty::ty_unboxed_closure(closure_did, _) => {
2362 let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
2363 let ref function_type = unboxed_closures.get(&closure_did)
2366 (function_type.sig.clone(), RustCall, true)
2368 _ => ccx.sess().bug("expected closure or function.")
2372 // Since index 0 is the return value of the llvm func, we start
2373 // at either 1 or 2 depending on whether there's an env slot or not
2374 let mut first_arg_offset = if has_env { 2 } else { 1 };
2375 let mut attrs = llvm::AttrBuilder::new();
2376 let ret_ty = fn_sig.output;
2378 // These have an odd calling convention, so we need to manually
2379 // unpack the input ty's
2380 let input_tys = match ty::get(fn_ty).sty {
2381 ty::ty_unboxed_closure(_, _) => {
2382 assert!(abi == RustCall);
2384 match ty::get(fn_sig.inputs[0]).sty {
2385 ty::ty_nil => Vec::new(),
2386 ty::ty_tup(ref inputs) => inputs.clone(),
2387 _ => ccx.sess().bug("expected tuple'd inputs")
2390 ty::ty_bare_fn(_) if abi == RustCall => {
2391 let inputs = vec![fn_sig.inputs[0]];
2393 match ty::get(fn_sig.inputs[1]).sty {
2394 ty::ty_nil => inputs,
2395 ty::ty_tup(ref t_in) => inputs.append(t_in.as_slice()),
2396 _ => ccx.sess().bug("expected tuple'd inputs")
2399 _ => fn_sig.inputs.clone()
2402 // A function pointer is called without the declaration
2403 // available, so we have to apply any attributes with ABI
2404 // implications directly to the call instruction. Right now,
2405 // the only attribute we need to worry about is `sret`.
2406 if type_of::return_uses_outptr(ccx, ret_ty) {
2407 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
2409 // The outptr can be noalias and nocapture because it's entirely
2410 // invisible to the program. We also know it's nonnull as well
2411 // as how many bytes we can dereference
2412 attrs.arg(1, llvm::StructRetAttribute)
2413 .arg(1, llvm::NoAliasAttribute)
2414 .arg(1, llvm::NoCaptureAttribute)
2415 .arg(1, llvm::DereferenceableAttribute(llret_sz));
2417 // Add one more since there's an outptr
2418 first_arg_offset += 1;
2420 // The `noalias` attribute on the return value is useful to a
2421 // function ptr caller.
2422 match ty::get(ret_ty).sty {
2423 // `~` pointer return values never alias because ownership
2425 ty::ty_uniq(it) if !ty::type_is_sized(ccx.tcx(), it) => {}
2427 attrs.ret(llvm::NoAliasAttribute);
2432 // We can also mark the return value as `dereferenceable` in certain cases
2433 match ty::get(ret_ty).sty {
2434 // These are not really pointers but pairs, (pointer, len)
2436 ty::ty_rptr(_, ty::mt { ty: it, .. }) if !ty::type_is_sized(ccx.tcx(), it) => {}
2437 ty::ty_uniq(inner) | ty::ty_rptr(_, ty::mt { ty: inner, .. }) => {
2438 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2439 attrs.ret(llvm::DereferenceableAttribute(llret_sz));
2444 match ty::get(ret_ty).sty {
2446 attrs.ret(llvm::ZExtAttribute);
2452 for (idx, &t) in input_tys.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2453 match ty::get(t).sty {
2454 // this needs to be first to prevent fat pointers from falling through
2455 _ if !type_is_immediate(ccx, t) => {
2456 let llarg_sz = llsize_of_real(ccx, type_of::type_of(ccx, t));
2458 // For non-immediate arguments the callee gets its own copy of
2459 // the value on the stack, so there are no aliases. It's also
2460 // program-invisible so can't possibly capture
2461 attrs.arg(idx, llvm::NoAliasAttribute)
2462 .arg(idx, llvm::NoCaptureAttribute)
2463 .arg(idx, llvm::DereferenceableAttribute(llarg_sz));
2467 attrs.arg(idx, llvm::ZExtAttribute);
2470 // `~` pointer parameters never alias because ownership is transferred
2471 ty::ty_uniq(inner) => {
2472 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2474 attrs.arg(idx, llvm::NoAliasAttribute)
2475 .arg(idx, llvm::DereferenceableAttribute(llsz));
2478 // The visit glue deals only with opaque pointers so we don't
2479 // actually know the concrete type of Self thus we don't know how
2480 // many bytes to mark as dereferenceable so instead we just mark
2481 // it as nonnull which still holds true
2482 ty::ty_rptr(b, ty::mt { ty: it, mutbl }) if match ty::get(it).sty {
2483 ty::ty_param(_) => true, _ => false
2484 } && mutbl == ast::MutMutable => {
2485 attrs.arg(idx, llvm::NoAliasAttribute)
2486 .arg(idx, llvm::NonNullAttribute);
2489 ReLateBound(_, BrAnon(_)) => {
2490 attrs.arg(idx, llvm::NoCaptureAttribute);
2496 // `&mut` pointer parameters never alias other parameters, or mutable global data
2498 // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
2499 // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on
2500 // memory dependencies rather than pointer equality
2501 ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable ||
2502 !ty::type_contents(ccx.tcx(), mt.ty).interior_unsafe() => {
2504 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2505 attrs.arg(idx, llvm::NoAliasAttribute)
2506 .arg(idx, llvm::DereferenceableAttribute(llsz));
2508 if mt.mutbl == ast::MutImmutable {
2509 attrs.arg(idx, llvm::ReadOnlyAttribute);
2513 ReLateBound(_, BrAnon(_)) => {
2514 attrs.arg(idx, llvm::NoCaptureAttribute);
2520 // When a reference in an argument has no named lifetime, it's impossible for that
2521 // reference to escape this function (returned or stored beyond the call by a closure).
2522 ty::ty_rptr(ReLateBound(_, BrAnon(_)), mt) => {
2523 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2524 attrs.arg(idx, llvm::NoCaptureAttribute)
2525 .arg(idx, llvm::DereferenceableAttribute(llsz));
2528 // & pointer parameters are also never null and we know exactly how
2529 // many bytes we can dereference
2530 ty::ty_rptr(_, mt) => {
2531 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2532 attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
2541 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2542 pub fn register_fn_llvmty(ccx: &CrateContext,
2545 node_id: ast::NodeId,
2547 llfty: Type) -> ValueRef {
2548 debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2550 let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
2551 finish_register_fn(ccx, sp, sym, node_id, llfn);
2555 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2556 match *sess.entry_fn.borrow() {
2557 Some((entry_id, _)) => node_id == entry_id,
2562 // Create a _rust_main(args: ~[str]) function which will be called from the
2563 // runtime rust_start function
2564 pub fn create_entry_wrapper(ccx: &CrateContext,
2566 main_llfn: ValueRef) {
2567 let et = ccx.sess().entry_type.get().unwrap();
2569 config::EntryMain => {
2570 create_entry_fn(ccx, main_llfn, true);
2572 config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2573 config::EntryNone => {} // Do nothing.
2576 fn create_entry_fn(ccx: &CrateContext,
2577 rust_main: ValueRef,
2578 use_start_lang_item: bool) {
2579 let llfty = Type::func([ccx.int_type(), Type::i8p(ccx).ptr_to()],
2582 let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
2584 // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2585 // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2586 if ccx.sess().targ_cfg.os == OsWindows {
2587 unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2590 let llbb = "top".with_c_str(|buf| {
2592 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, buf)
2595 let bld = ccx.raw_builder();
2597 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2599 let (start_fn, args) = if use_start_lang_item {
2600 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2602 Err(s) => { ccx.sess().fatal(s.as_slice()); }
2604 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2605 get_item_val(ccx, start_def_id.node)
2607 let start_fn_type = csearch::get_type(ccx.tcx(),
2609 trans_external_path(ccx, start_def_id, start_fn_type)
2613 let opaque_rust_main = "rust_main".with_c_str(|buf| {
2614 llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
2625 debug!("using user-defined start fn");
2627 get_param(llfn, 0 as c_uint),
2628 get_param(llfn, 1 as c_uint)
2634 let result = llvm::LLVMBuildCall(bld,
2637 args.len() as c_uint,
2640 llvm::LLVMBuildRet(bld, result);
2645 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2646 ty: ty::t, attrs: &[ast::Attribute]) -> String {
2647 match ccx.external_srcs().borrow().find(&id) {
2649 let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2650 debug!("found item {} in other crate...", sym);
2656 match attr::first_attr_value_str_by_name(attrs, "export_name") {
2657 // Use provided name
2658 Some(name) => name.get().to_string(),
2660 _ => ccx.tcx().map.with_path(id, |mut path| {
2661 if attr::contains_name(attrs, "no_mangle") {
2663 path.last().unwrap().to_string()
2665 match weak_lang_items::link_name(attrs) {
2666 Some(name) => name.get().to_string(),
2668 // Usual name mangling
2669 mangle_exported_name(ccx, path, ty, id)
2677 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2678 debug!("get_item_val(id=`{:?}`)", id);
2680 match ccx.item_vals().borrow().find_copy(&id) {
2681 Some(v) => return v,
2685 let item = ccx.tcx().map.get(id);
2686 let val = match item {
2687 ast_map::NodeItem(i) => {
2688 let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2689 let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2691 let v = match i.node {
2692 ast::ItemStatic(_, mutbl, ref expr) => {
2693 // If this static came from an external crate, then
2694 // we need to get the symbol from csearch instead of
2695 // using the current crate's name/version
2696 // information in the hash of the symbol
2697 debug!("making {}", sym);
2698 let is_local = !ccx.external_srcs().borrow().contains_key(&id);
2700 // We need the translated value here, because for enums the
2701 // LLVM type is not fully determined by the Rust type.
2702 let (v, inlineable, _) = consts::const_expr(ccx, &**expr, is_local);
2703 ccx.const_values().borrow_mut().insert(id, v);
2704 let mut inlineable = inlineable;
2707 let llty = llvm::LLVMTypeOf(v);
2708 let g = sym.as_slice().with_c_str(|buf| {
2709 llvm::LLVMAddGlobal(ccx.llmod(), llty, buf)
2712 // Apply the `unnamed_addr` attribute if
2714 if !ast_util::static_has_significant_address(
2716 i.attrs.as_slice()) {
2717 llvm::SetUnnamedAddr(g, true);
2719 // This is a curious case where we must make
2720 // all of these statics inlineable. If a
2721 // global is not tagged as `#[inline(never)]`,
2722 // then LLVM won't coalesce globals unless they
2723 // have an internal linkage type. This means that
2724 // external crates cannot use this global.
2725 // This is a problem for things like inner
2726 // statics in generic functions, because the
2727 // function will be inlined into another
2728 // crate and then attempt to link to the
2729 // static in the original crate, only to
2730 // find that it's not there. On the other
2731 // side of inlining, the crates knows to
2732 // not declare this static as
2733 // available_externally (because it isn't)
2737 if attr::contains_name(i.attrs.as_slice(),
2739 llvm::set_thread_local(g, true);
2743 debug!("{} not inlined", sym);
2744 ccx.non_inlineable_statics().borrow_mut()
2748 ccx.item_symbols().borrow_mut().insert(i.id, sym);
2753 ast::ItemFn(_, _, abi, _, _) => {
2754 let llfn = if abi == Rust {
2755 register_fn(ccx, i.span, sym, i.id, ty)
2757 foreign::register_rust_fn_with_foreign_abi(ccx,
2762 set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2766 _ => fail!("get_item_val: weird result in table")
2769 match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2771 Some(sect) => unsafe {
2772 sect.get().with_c_str(|buf| {
2773 llvm::LLVMSetSection(v, buf);
2782 ast_map::NodeTraitItem(trait_method) => {
2783 debug!("get_item_val(): processing a NodeTraitItem");
2784 match *trait_method {
2785 ast::RequiredMethod(_) => {
2786 ccx.sess().bug("unexpected variant: required trait method in \
2789 ast::ProvidedMethod(m) => {
2790 register_method(ccx, id, &*m)
2795 ast_map::NodeImplItem(ii) => {
2797 ast::MethodImplItem(m) => register_method(ccx, id, &*m),
2801 ast_map::NodeForeignItem(ni) => {
2803 ast::ForeignItemFn(..) => {
2804 let abi = ccx.tcx().map.get_foreign_abi(id);
2805 let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2806 let name = foreign::link_name(&*ni);
2807 foreign::register_foreign_item_fn(ccx, abi, ty,
2808 name.get().as_slice(),
2811 ast::ForeignItemStatic(..) => {
2812 foreign::register_static(ccx, &*ni)
2817 ast_map::NodeVariant(ref v) => {
2819 let args = match v.node.kind {
2820 ast::TupleVariantKind(ref args) => args,
2821 ast::StructVariantKind(_) => {
2822 fail!("struct variant kind unexpected in get_item_val")
2825 assert!(args.len() != 0u);
2826 let ty = ty::node_id_to_type(ccx.tcx(), id);
2827 let parent = ccx.tcx().map.get_parent(id);
2828 let enm = ccx.tcx().map.expect_item(parent);
2829 let sym = exported_name(ccx,
2832 enm.attrs.as_slice());
2834 llfn = match enm.node {
2835 ast::ItemEnum(_, _) => {
2836 register_fn(ccx, (*v).span, sym, id, ty)
2838 _ => fail!("NodeVariant, shouldn't happen")
2840 set_inline_hint(llfn);
2844 ast_map::NodeStructCtor(struct_def) => {
2845 // Only register the constructor if this is a tuple-like struct.
2846 let ctor_id = match struct_def.ctor_id {
2848 ccx.sess().bug("attempt to register a constructor of \
2849 a non-tuple-like struct")
2851 Some(ctor_id) => ctor_id,
2853 let parent = ccx.tcx().map.get_parent(id);
2854 let struct_item = ccx.tcx().map.expect_item(parent);
2855 let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2856 let sym = exported_name(ccx,
2861 let llfn = register_fn(ccx, struct_item.span,
2863 set_inline_hint(llfn);
2868 ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2869 variant).as_slice())
2873 // All LLVM globals and functions are initially created as external-linkage
2874 // declarations. If `trans_item`/`trans_fn` later turns the declaration
2875 // into a definition, it adjusts the linkage then (using `update_linkage`).
2877 // The exception is foreign items, which have their linkage set inside the
2878 // call to `foreign::register_*` above. We don't touch the linkage after
2879 // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2880 // other item translation functions do).
2882 ccx.item_vals().borrow_mut().insert(id, val);
2886 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2887 m: &ast::Method) -> ValueRef {
2888 let mty = ty::node_id_to_type(ccx.tcx(), id);
2890 let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2892 let llfn = register_fn(ccx, m.span, sym, id, mty);
2893 set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2897 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2899 return llvm::LLVMConstPtrToInt(v, ccx.int_type().to_ref());
2903 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2904 ie: encoder::EncodeInlinedItem<'a>)
2905 -> encoder::EncodeParams<'a, 'tcx> {
2906 encoder::EncodeParams {
2907 diag: cx.sess().diagnostic(),
2909 reexports2: cx.exp_map2(),
2910 item_symbols: cx.item_symbols(),
2911 non_inlineable_statics: cx.non_inlineable_statics(),
2912 link_meta: cx.link_meta(),
2913 cstore: &cx.sess().cstore,
2914 encode_inlined_item: ie,
2915 reachable: cx.reachable(),
2919 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2922 let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2923 *ty != config::CrateTypeExecutable
2929 let encode_inlined_item: encoder::EncodeInlinedItem =
2930 |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii);
2932 let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2933 let metadata = encoder::encode_metadata(encode_parms, krate);
2934 let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2935 .append(match flate::deflate_bytes(metadata.as_slice()) {
2936 Some(compressed) => compressed,
2938 cx.sess().fatal("failed to compress metadata")
2941 let llmeta = C_bytes_in_context(cx.metadata_llcx(), compressed.as_slice());
2942 let llconst = C_struct_in_context(cx.metadata_llcx(), [llmeta], false);
2943 let name = format!("rust_metadata_{}_{}",
2944 cx.link_meta().crate_name,
2945 cx.link_meta().crate_hash);
2946 let llglobal = name.with_c_str(|buf| {
2948 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf)
2952 llvm::LLVMSetInitializer(llglobal, llconst);
2953 let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2954 name.unwrap_or("rust_metadata").with_c_str(|buf| {
2955 llvm::LLVMSetSection(llglobal, buf)
2961 /// Find any symbols that are defined in one compilation unit, but not declared
2962 /// in any other compilation unit. Give these symbols internal linkage.
2963 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
2964 use std::c_str::CString;
2967 let mut declared = HashSet::new();
2969 let iter_globals = |llmod| {
2971 cur: llvm::LLVMGetFirstGlobal(llmod),
2972 step: llvm::LLVMGetNextGlobal,
2976 let iter_functions = |llmod| {
2978 cur: llvm::LLVMGetFirstFunction(llmod),
2979 step: llvm::LLVMGetNextFunction,
2983 // Collect all external declarations in all compilation units.
2984 for ccx in cx.iter() {
2985 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2986 let linkage = llvm::LLVMGetLinkage(val);
2987 // We only care about external declarations (not definitions)
2988 // and available_externally definitions.
2989 if !(linkage == llvm::ExternalLinkage as c_uint &&
2990 llvm::LLVMIsDeclaration(val) != 0) &&
2991 !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2995 let name = CString::new(llvm::LLVMGetValueName(val), false);
2996 declared.insert(name);
3000 // Examine each external definition. If the definition is not used in
3001 // any other compilation unit, and is not reachable from other crates,
3002 // then give it internal linkage.
3003 for ccx in cx.iter() {
3004 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
3005 // We only care about external definitions.
3006 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
3007 llvm::LLVMIsDeclaration(val) == 0) {
3011 let name = CString::new(llvm::LLVMGetValueName(val), false);
3012 if !declared.contains(&name) &&
3013 !reachable.contains_equiv(&name.as_str().unwrap()) {
3014 llvm::SetLinkage(val, llvm::InternalLinkage);
3023 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
3026 impl Iterator<ValueRef> for ValueIter {
3027 fn next(&mut self) -> Option<ValueRef> {
3030 self.cur = unsafe { (self.step)(old) };
3039 pub fn trans_crate(krate: ast::Crate,
3040 analysis: CrateAnalysis) -> (ty::ctxt, CrateTranslation) {
3041 let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
3043 // Before we touch LLVM, make sure that multithreading is enabled.
3045 use std::sync::{Once, ONCE_INIT};
3046 static mut INIT: Once = ONCE_INIT;
3047 static mut POISONED: bool = false;
3049 if llvm::LLVMStartMultithreaded() != 1 {
3050 // use an extra bool to make sure that all future usage of LLVM
3051 // cannot proceed despite the Once not running more than once.
3057 tcx.sess.bug("couldn't enable multi-threaded LLVM");
3061 let link_meta = link::build_link_meta(&tcx.sess, &krate, name);
3063 let codegen_units = tcx.sess.opts.cg.codegen_units;
3064 let shared_ccx = SharedCrateContext::new(link_meta.crate_name.as_slice(),
3073 let ccx = shared_ccx.get_ccx(0);
3075 // First, verify intrinsics.
3076 intrinsic::check_intrinsics(&ccx);
3078 // Next, translate the module.
3080 let _icx = push_ctxt("text");
3081 trans_mod(&ccx, &krate.module);
3085 for ccx in shared_ccx.iter() {
3086 glue::emit_tydescs(&ccx);
3087 if ccx.sess().opts.debuginfo != NoDebugInfo {
3088 debuginfo::finalize(&ccx);
3092 // Translate the metadata.
3093 let metadata = write_metadata(&shared_ccx, &krate);
3095 if shared_ccx.sess().trans_stats() {
3096 let stats = shared_ccx.stats();
3097 println!("--- trans stats ---");
3098 println!("n_static_tydescs: {}", stats.n_static_tydescs.get());
3099 println!("n_glues_created: {}", stats.n_glues_created.get());
3100 println!("n_null_glues: {}", stats.n_null_glues.get());
3101 println!("n_real_glues: {}", stats.n_real_glues.get());
3103 println!("n_fns: {}", stats.n_fns.get());
3104 println!("n_monos: {}", stats.n_monos.get());
3105 println!("n_inlines: {}", stats.n_inlines.get());
3106 println!("n_closures: {}", stats.n_closures.get());
3107 println!("fn stats:");
3108 stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
3109 insns_b.cmp(&insns_a)
3111 for tuple in stats.fn_stats.borrow().iter() {
3113 (ref name, ms, insns) => {
3114 println!("{} insns, {} ms, {}", insns, ms, *name);
3119 if shared_ccx.sess().count_llvm_insns() {
3120 for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
3121 println!("{:7u} {}", *v, *k);
3125 let modules = shared_ccx.iter()
3126 .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
3129 let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
3130 shared_ccx.item_symbols().borrow().find(id).map(|s| s.to_string())
3133 // For the purposes of LTO, we add to the reachable set all of the upstream
3134 // reachable extern fns. These functions are all part of the public ABI of
3135 // the final product, so LTO needs to preserve them.
3136 shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
3137 let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
3138 reachable.extend(syms.move_iter().map(|did| {
3139 csearch::get_symbol(&shared_ccx.sess().cstore, did)
3143 // Make sure that some other crucial symbols are not eliminated from the
3144 // module. This includes the main function, the crate map (used for debug
3145 // log settings and I/O), and finally the curious rust_stack_exhausted
3146 // symbol. This symbol is required for use by the libmorestack library that
3147 // we link in, so we must ensure that this symbol is not internalized (if
3148 // defined in the crate).
3149 reachable.push("main".to_string());
3150 reachable.push("rust_stack_exhausted".to_string());
3152 // referenced from .eh_frame section on some platforms
3153 reachable.push("rust_eh_personality".to_string());
3154 // referenced from rt/rust_try.ll
3155 reachable.push("rust_eh_personality_catch".to_string());
3157 if codegen_units > 1 {
3158 internalize_symbols(&shared_ccx, &reachable.iter().map(|x| x.clone()).collect());
3161 let metadata_module = ModuleTranslation {
3162 llcx: shared_ccx.metadata_llcx(),
3163 llmod: shared_ccx.metadata_llmod(),
3165 let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
3166 let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
3168 let translation = CrateTranslation {
3170 metadata_module: metadata_module,
3173 reachable: reachable,
3174 crate_formats: formats,
3175 no_builtins: no_builtins,
3178 (shared_ccx.take_tcx(), translation)