1 // Copyright 2012-2015 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 //! 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 //! 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 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`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 super::CrateTranslation;
29 use super::ModuleLlvm;
30 use super::ModuleSource;
31 use super::ModuleTranslation;
33 use assert_module_sources;
35 use back::linker::LinkerInfo;
36 use llvm::{Linkage, ValueRef, Vector, get_param};
38 use rustc::hir::def::Def;
39 use rustc::hir::def_id::DefId;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use rustc::ty::subst::Substs;
43 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
44 use rustc::ty::adjustment::CustomCoerceUnsized;
45 use rustc::dep_graph::{DepNode, WorkProduct};
46 use rustc::hir::map as hir_map;
47 use rustc::util::common::time;
48 use session::config::{self, NoDebugInfo};
49 use rustc_incremental::IncrementalHashesMap;
51 use abi::{self, Abi, FnType};
55 use builder::{Builder, noname};
57 use common::{Block, C_bool, C_bytes_in_context, C_i32, C_uint};
58 use collector::{self, TransItemCollectionMode};
59 use common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
60 use common::{CrateContext, FunctionContext};
62 use common::{fulfill_obligation};
63 use common::{type_is_zero_size, val_ty};
66 use context::{SharedCrateContext, CrateContextList};
67 use debuginfo::{self, DebugLoc};
70 use machine::{llalign_of_min, llsize_of};
73 use monomorphize::{self, Instance};
74 use partitioning::{self, PartitioningStrategy, CodegenUnit};
75 use symbol_map::SymbolMap;
76 use symbol_names_test;
77 use trans_item::TransItem;
82 use util::nodemap::{NodeSet, FnvHashMap, FnvHashSet};
84 use arena::TypedArena;
86 use std::ffi::{CStr, CString};
88 use std::cell::{Cell, RefCell};
93 use syntax_pos::{Span, DUMMY_SP};
99 static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
104 pub fn with_insn_ctxt<F>(blk: F)
105 where F: FnOnce(&[&'static str])
107 TASK_LOCAL_INSN_KEY.with(move |slot| {
108 slot.borrow().as_ref().map(move |s| blk(s));
112 pub fn init_insn_ctxt() {
113 TASK_LOCAL_INSN_KEY.with(|slot| {
114 *slot.borrow_mut() = Some(Vec::new());
118 pub struct _InsnCtxt {
119 _cannot_construct_outside_of_this_module: (),
122 impl Drop for _InsnCtxt {
124 TASK_LOCAL_INSN_KEY.with(|slot| {
125 if let Some(ctx) = slot.borrow_mut().as_mut() {
132 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
133 debug!("new InsnCtxt: {}", s);
134 TASK_LOCAL_INSN_KEY.with(|slot| {
135 if let Some(ctx) = slot.borrow_mut().as_mut() {
140 _cannot_construct_outside_of_this_module: (),
144 pub struct StatRecorder<'a, 'tcx: 'a> {
145 ccx: &'a CrateContext<'a, 'tcx>,
146 name: Option<String>,
150 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
151 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
152 let istart = ccx.stats().n_llvm_insns.get();
161 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
163 if self.ccx.sess().trans_stats() {
164 let iend = self.ccx.stats().n_llvm_insns.get();
169 .push((self.name.take().unwrap(), iend - self.istart));
170 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
171 // Reset LLVM insn count to avoid compound costs.
172 self.ccx.stats().n_llvm_insns.set(self.istart);
177 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
178 StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
181 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
182 StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
185 pub fn get_meta_builder(b: &Builder, fat_ptr: ValueRef) -> ValueRef {
186 b.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
189 pub fn get_dataptr_builder(b: &Builder, fat_ptr: ValueRef) -> ValueRef {
190 b.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
193 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, info_ty: Ty<'tcx>, it: LangItem) -> DefId {
194 match bcx.tcx().lang_items.require(it) {
197 bcx.sess().fatal(&format!("allocation of `{}` {}", info_ty, s));
202 // The following malloc_raw_dyn* functions allocate a box to contain
203 // a given type, but with a potentially dynamic size.
205 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
211 -> Result<'blk, 'tcx> {
212 let _icx = push_ctxt("malloc_raw_exchange");
215 let def_id = require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem);
216 let r = Callee::def(bcx.ccx(), def_id, bcx.tcx().intern_substs(&[]))
217 .call(bcx, debug_loc, &[size, align], None);
219 Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
223 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
225 -> llvm::IntPredicate {
227 hir::BiEq => llvm::IntEQ,
228 hir::BiNe => llvm::IntNE,
229 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
230 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
231 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
232 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
234 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
241 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
243 hir::BiEq => llvm::RealOEQ,
244 hir::BiNe => llvm::RealUNE,
245 hir::BiLt => llvm::RealOLT,
246 hir::BiLe => llvm::RealOLE,
247 hir::BiGt => llvm::RealOGT,
248 hir::BiGe => llvm::RealOGE,
250 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
257 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
265 let signed = match t.sty {
267 let cmp = bin_op_to_fcmp_predicate(op);
268 return SExt(bcx, FCmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty);
270 ty::TyUint(_) => false,
271 ty::TyInt(_) => true,
272 _ => bug!("compare_simd_types: invalid SIMD type"),
275 let cmp = bin_op_to_icmp_predicate(op, signed);
276 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
277 // to get the correctly sized type. This will compile to a single instruction
278 // once the IR is converted to assembly if the SIMD instruction is supported
279 // by the target architecture.
280 SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty)
283 /// Retrieve the information we are losing (making dynamic) in an unsizing
286 /// The `old_info` argument is a bit funny. It is intended for use
287 /// in an upcast, where the new vtable for an object will be drived
288 /// from the old one.
289 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
292 old_info: Option<ValueRef>)
294 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
295 match (&source.sty, &target.sty) {
296 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
297 (&ty::TyTrait(_), &ty::TyTrait(_)) => {
298 // For now, upcasts are limited to changes in marker
299 // traits, and hence never actually require an actual
300 // change to the vtable.
301 old_info.expect("unsized_info: missing old info for trait upcast")
303 (_, &ty::TyTrait(ref data)) => {
304 let trait_ref = data.principal.with_self_ty(ccx.tcx(), source);
305 let trait_ref = ccx.tcx().erase_regions(&trait_ref);
306 consts::ptrcast(meth::get_vtable(ccx, trait_ref),
307 Type::vtable_ptr(ccx))
309 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
315 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
316 pub fn unsize_thin_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
320 -> (ValueRef, ValueRef) {
321 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
322 match (&src_ty.sty, &dst_ty.sty) {
323 (&ty::TyBox(a), &ty::TyBox(b)) |
324 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
325 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
326 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
327 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
328 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
329 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
330 assert!(common::type_is_sized(bcx.tcx(), a));
331 let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), b).ptr_to();
332 (PointerCast(bcx, src, ptr_ty),
333 unsized_info(bcx.ccx(), a, b, None))
335 _ => bug!("unsize_thin_ptr: called on bad types"),
339 /// Coerce `src`, which is a reference to a value of type `src_ty`,
340 /// to a value of type `dst_ty` and store the result in `dst`
341 pub fn coerce_unsized_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
346 match (&src_ty.sty, &dst_ty.sty) {
347 (&ty::TyBox(..), &ty::TyBox(..)) |
348 (&ty::TyRef(..), &ty::TyRef(..)) |
349 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
350 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
351 let (base, info) = if common::type_is_fat_ptr(bcx.tcx(), src_ty) {
352 // fat-ptr to fat-ptr unsize preserves the vtable
353 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
354 // So we need to pointercast the base to ensure
355 // the types match up.
356 let (base, info) = load_fat_ptr(bcx, src, src_ty);
357 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx(), dst_ty);
358 let base = PointerCast(bcx, base, llcast_ty);
361 let base = load_ty(bcx, src, src_ty);
362 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
364 store_fat_ptr(bcx, base, info, dst, dst_ty);
367 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
368 assert_eq!(def_a, def_b);
370 let src_fields = def_a.variants[0].fields.iter().map(|f| {
371 monomorphize::field_ty(bcx.tcx(), substs_a, f)
373 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
374 monomorphize::field_ty(bcx.tcx(), substs_b, f)
377 let src = adt::MaybeSizedValue::sized(src);
378 let dst = adt::MaybeSizedValue::sized(dst);
380 let iter = src_fields.zip(dst_fields).enumerate();
381 for (i, (src_fty, dst_fty)) in iter {
382 if type_is_zero_size(bcx.ccx(), dst_fty) {
386 let src_f = adt::trans_field_ptr(bcx, src_ty, src, Disr(0), i);
387 let dst_f = adt::trans_field_ptr(bcx, dst_ty, dst, Disr(0), i);
388 if src_fty == dst_fty {
389 memcpy_ty(bcx, dst_f, src_f, src_fty);
391 coerce_unsized_into(bcx, src_f, src_fty, dst_f, dst_fty);
395 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
401 pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>,
404 -> CustomCoerceUnsized {
405 let trait_ref = ty::Binder(ty::TraitRef {
406 def_id: scx.tcx().lang_items.coerce_unsized_trait().unwrap(),
407 substs: scx.tcx().mk_substs_trait(source_ty, &[target_ty])
410 match fulfill_obligation(scx, DUMMY_SP, trait_ref) {
411 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
412 scx.tcx().custom_coerce_unsized_kind(impl_def_id)
415 bug!("invalid CoerceUnsized vtable: {:?}", vtable);
420 pub fn cast_shift_expr_rhs(cx: Block, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
421 cast_shift_rhs(op, lhs, rhs, |a, b| Trunc(cx, a, b), |a, b| ZExt(cx, a, b))
424 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
428 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
429 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
432 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
438 where F: FnOnce(ValueRef, Type) -> ValueRef,
439 G: FnOnce(ValueRef, Type) -> ValueRef
441 // Shifts may have any size int on the rhs
443 let mut rhs_llty = val_ty(rhs);
444 let mut lhs_llty = val_ty(lhs);
445 if rhs_llty.kind() == Vector {
446 rhs_llty = rhs_llty.element_type()
448 if lhs_llty.kind() == Vector {
449 lhs_llty = lhs_llty.element_type()
451 let rhs_sz = rhs_llty.int_width();
452 let lhs_sz = lhs_llty.int_width();
455 } else if lhs_sz > rhs_sz {
456 // FIXME (#1877: If shifting by negative
457 // values becomes not undefined then this is wrong.
467 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
471 -> (ValueRef, Block<'blk, 'tcx>) {
472 let _icx = push_ctxt("invoke_");
473 if bcx.unreachable.get() {
474 return (C_null(Type::i8(bcx.ccx())), bcx);
477 if need_invoke(bcx) {
478 debug!("invoking {:?} at {:?}", Value(llfn), bcx.llbb);
479 for &llarg in llargs {
480 debug!("arg: {:?}", Value(llarg));
482 let normal_bcx = bcx.fcx.new_block("normal-return");
483 let landing_pad = bcx.fcx.get_landing_pad();
485 let llresult = Invoke(bcx,
491 return (llresult, normal_bcx);
493 debug!("calling {:?} at {:?}", Value(llfn), bcx.llbb);
494 for &llarg in llargs {
495 debug!("arg: {:?}", Value(llarg));
498 let llresult = Call(bcx, llfn, &llargs[..], debug_loc);
499 return (llresult, bcx);
503 /// Returns whether this session's target will use SEH-based unwinding.
505 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
506 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
507 /// 64-bit MinGW) instead of "full SEH".
508 pub fn wants_msvc_seh(sess: &Session) -> bool {
509 sess.target.target.options.is_like_msvc
512 pub fn avoid_invoke(bcx: Block) -> bool {
513 bcx.sess().no_landing_pads() || bcx.lpad().is_some()
516 pub fn need_invoke(bcx: Block) -> bool {
517 if avoid_invoke(bcx) {
520 bcx.fcx.needs_invoke()
524 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
525 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
526 b.call(assume_intrinsic, &[val], None);
529 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
530 /// differs from the type used for SSA values. Also handles various special cases where the type
531 /// gives us better information about what we are loading.
532 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
533 if cx.unreachable.get() {
534 return C_undef(type_of::type_of(cx.ccx(), t));
536 load_ty_builder(&B(cx), ptr, t)
539 pub fn load_ty_builder<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
541 if type_is_zero_size(ccx, t) {
542 return C_undef(type_of::type_of(ccx, t));
546 let global = llvm::LLVMIsAGlobalVariable(ptr);
547 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
548 let val = llvm::LLVMGetInitializer(global);
551 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
559 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False), Type::i1(ccx))
560 } else if t.is_char() {
561 // a char is a Unicode codepoint, and so takes values from 0
562 // to 0x10FFFF inclusive only.
563 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False)
564 } else if (t.is_region_ptr() || t.is_unique()) &&
565 !common::type_is_fat_ptr(ccx.tcx(), t) {
572 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
573 /// differs from the type used for SSA values.
574 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
575 if cx.unreachable.get() {
579 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
581 if common::type_is_fat_ptr(cx.tcx(), t) {
582 let lladdr = ExtractValue(cx, v, abi::FAT_PTR_ADDR);
583 let llextra = ExtractValue(cx, v, abi::FAT_PTR_EXTRA);
584 store_fat_ptr(cx, lladdr, llextra, dst, t);
586 Store(cx, from_immediate(cx, v), dst);
590 pub fn store_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
595 // FIXME: emit metadata
596 Store(cx, data, get_dataptr(cx, dst));
597 Store(cx, extra, get_meta(cx, dst));
600 pub fn load_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
603 -> (ValueRef, ValueRef)
605 if cx.unreachable.get() {
607 return (Load(cx, get_dataptr(cx, src)),
608 Load(cx, get_meta(cx, src)));
611 load_fat_ptr_builder(&B(cx), src, ty)
614 pub fn load_fat_ptr_builder<'a, 'tcx>(
615 b: &Builder<'a, 'tcx>,
618 -> (ValueRef, ValueRef)
621 let ptr = get_dataptr_builder(b, src);
622 let ptr = if t.is_region_ptr() || t.is_unique() {
628 // FIXME: emit metadata on `meta`.
629 let meta = b.load(get_meta_builder(b, src));
634 pub fn from_immediate(bcx: Block, val: ValueRef) -> ValueRef {
635 if val_ty(val) == Type::i1(bcx.ccx()) {
636 ZExt(bcx, val, Type::i8(bcx.ccx()))
642 pub fn to_immediate(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
644 Trunc(bcx, val, Type::i1(bcx.ccx()))
650 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, val: ValueRef, f: F) -> Block<'blk, 'tcx>
651 where F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>
653 let _icx = push_ctxt("with_cond");
655 if bcx.unreachable.get() || common::const_to_opt_uint(val) == Some(0) {
660 let next_cx = fcx.new_block("next");
661 let cond_cx = fcx.new_block("cond");
662 CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
663 let after_cx = f(cond_cx);
664 if !after_cx.terminated.get() {
665 Br(after_cx, next_cx.llbb, DebugLoc::None);
670 pub enum Lifetime { Start, End }
672 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
673 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
674 // and the intrinsic for `lt` and passes them to `emit`, which is in
675 // charge of generating code to call the passed intrinsic on whatever
676 // block of generated code is targetted for the intrinsic.
678 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
679 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
680 fn core_lifetime_emit<'blk, 'tcx, F>(ccx: &'blk CrateContext<'blk, 'tcx>,
684 where F: FnOnce(&'blk CrateContext<'blk, 'tcx>, machine::llsize, ValueRef)
686 if ccx.sess().opts.optimize == config::OptLevel::No {
690 let _icx = push_ctxt(match lt {
691 Lifetime::Start => "lifetime_start",
692 Lifetime::End => "lifetime_end"
695 let size = machine::llsize_of_alloc(ccx, val_ty(ptr).element_type());
700 let lifetime_intrinsic = ccx.get_intrinsic(match lt {
701 Lifetime::Start => "llvm.lifetime.start",
702 Lifetime::End => "llvm.lifetime.end"
704 emit(ccx, size, lifetime_intrinsic)
708 pub fn call(self, b: &Builder, ptr: ValueRef) {
709 core_lifetime_emit(b.ccx, ptr, self, |ccx, size, lifetime_intrinsic| {
710 let ptr = b.pointercast(ptr, Type::i8p(ccx));
711 b.call(lifetime_intrinsic, &[C_u64(ccx, size), ptr], None);
716 pub fn call_lifetime_start(bcx: Block, ptr: ValueRef) {
717 if !bcx.unreachable.get() {
718 Lifetime::Start.call(&bcx.build(), ptr);
722 pub fn call_lifetime_end(bcx: Block, ptr: ValueRef) {
723 if !bcx.unreachable.get() {
724 Lifetime::End.call(&bcx.build(), ptr);
728 // Generates code for resumption of unwind at the end of a landing pad.
729 pub fn trans_unwind_resume(bcx: Block, lpval: ValueRef) {
730 if !bcx.sess().target.target.options.custom_unwind_resume {
733 let exc_ptr = ExtractValue(bcx, lpval, 0);
734 bcx.fcx.eh_unwind_resume()
735 .call(bcx, DebugLoc::None, &[exc_ptr], None);
739 pub fn call_memcpy<'bcx, 'tcx>(b: &Builder<'bcx, 'tcx>,
744 let _icx = push_ctxt("call_memcpy");
746 let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
747 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
748 let memcpy = ccx.get_intrinsic(&key);
749 let src_ptr = b.pointercast(src, Type::i8p(ccx));
750 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
751 let size = b.intcast(n_bytes, ccx.int_type());
752 let align = C_i32(ccx, align as i32);
753 let volatile = C_bool(ccx, false);
754 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
757 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, dst: ValueRef, src: ValueRef, t: Ty<'tcx>) {
758 let _icx = push_ctxt("memcpy_ty");
761 if type_is_zero_size(ccx, t) || bcx.unreachable.get() {
765 if t.is_structural() {
766 let llty = type_of::type_of(ccx, t);
767 let llsz = llsize_of(ccx, llty);
768 let llalign = type_of::align_of(ccx, t);
769 call_memcpy(&B(bcx), dst, src, llsz, llalign as u32);
770 } else if common::type_is_fat_ptr(bcx.tcx(), t) {
771 let (data, extra) = load_fat_ptr(bcx, src, t);
772 store_fat_ptr(bcx, data, extra, dst, t);
774 store_ty(bcx, load_ty(bcx, src, t), dst, t);
778 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
779 if cx.unreachable.get() {
782 let _icx = push_ctxt("init_zero_mem");
784 memfill(&B(bcx), llptr, t, 0);
787 // Always use this function instead of storing a constant byte to the memory
788 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
789 // allocation for large data structures, and the generated code will be
790 // awful. (A telltale sign of this is large quantities of
791 // `mov [byte ptr foo],0` in the generated code.)
792 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
793 let _icx = push_ctxt("memfill");
795 let llty = type_of::type_of(ccx, ty);
796 let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
797 let llzeroval = C_u8(ccx, byte);
798 let size = machine::llsize_of(ccx, llty);
799 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
800 call_memset(b, llptr, llzeroval, size, align, false);
803 pub fn call_memset<'bcx, 'tcx>(b: &Builder<'bcx, 'tcx>,
810 let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
811 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
812 let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
813 let volatile = C_bool(ccx, volatile);
814 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None);
817 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
819 name: &str) -> ValueRef {
820 assert!(!ty.has_param_types());
821 alloca(bcx, type_of::type_of(bcx.ccx(), ty), name)
824 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
825 let _icx = push_ctxt("alloca");
826 if cx.unreachable.get() {
828 return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
831 DebugLoc::None.apply(cx.fcx);
835 impl<'blk, 'tcx> FunctionContext<'blk, 'tcx> {
836 /// Create a function context for the given function.
837 /// Beware that you must call `fcx.init` or `fcx.bind_args`
838 /// before doing anything with the returned function context.
839 pub fn new(ccx: &'blk CrateContext<'blk, 'tcx>,
842 definition: Option<(Instance<'tcx>, &ty::FnSig<'tcx>, Abi)>,
843 block_arena: &'blk TypedArena<common::BlockS<'blk, 'tcx>>)
844 -> FunctionContext<'blk, 'tcx> {
845 let (param_substs, def_id) = match definition {
846 Some((instance, ..)) => {
847 common::validate_substs(instance.substs);
848 (instance.substs, Some(instance.def))
850 None => (ccx.tcx().intern_substs(&[]), None)
853 let local_id = def_id.and_then(|id| ccx.tcx().map.as_local_node_id(id));
855 debug!("FunctionContext::new({})",
856 definition.map_or(String::new(), |d| d.0.to_string()));
858 let no_debug = if let Some(id) = local_id {
859 ccx.tcx().map.attrs(id)
860 .iter().any(|item| item.check_name("no_debug"))
861 } else if let Some(def_id) = def_id {
862 ccx.sess().cstore.item_attrs(def_id)
863 .iter().any(|item| item.check_name("no_debug"))
868 let mir = def_id.map(|id| ccx.tcx().item_mir(id));
870 let debug_context = if let (false, Some((instance, sig, abi)), &Some(ref mir)) =
871 (no_debug, definition, &mir) {
872 debuginfo::create_function_debug_context(ccx, instance, sig, abi, llfndecl, mir)
874 debuginfo::empty_function_debug_context(ccx)
880 llretslotptr: Cell::new(None),
881 param_env: ccx.tcx().empty_parameter_environment(),
882 alloca_insert_pt: Cell::new(None),
883 landingpad_alloca: Cell::new(None),
885 param_substs: param_substs,
887 block_arena: block_arena,
888 lpad_arena: TypedArena::new(),
890 debug_context: debug_context,
891 scopes: RefCell::new(Vec::new()),
895 /// Performs setup on a newly created function, creating the entry
896 /// scope block and allocating space for the return pointer.
897 pub fn init(&'blk self, skip_retptr: bool) -> Block<'blk, 'tcx> {
898 let entry_bcx = self.new_block("entry-block");
900 // Use a dummy instruction as the insertion point for all allocas.
901 // This is later removed in FunctionContext::cleanup.
902 self.alloca_insert_pt.set(Some(unsafe {
903 Load(entry_bcx, C_null(Type::i8p(self.ccx)));
904 llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
907 if !self.fn_ty.ret.is_ignore() && !skip_retptr {
908 // We normally allocate the llretslotptr, unless we
909 // have been instructed to skip it for immediate return
910 // values, or there is nothing to return at all.
912 // We create an alloca to hold a pointer of type `ret.original_ty`
913 // which will hold the pointer to the right alloca which has the
915 let llty = self.fn_ty.ret.memory_ty(self.ccx);
916 // But if there are no nested returns, we skip the indirection
917 // and have a single retslot
918 let slot = if self.fn_ty.ret.is_indirect() {
919 get_param(self.llfn, 0)
921 AllocaFcx(self, llty, "sret_slot")
924 self.llretslotptr.set(Some(slot));
930 /// Ties up the llstaticallocas -> llloadenv -> lltop edges,
931 /// and builds the return block.
932 pub fn finish(&'blk self, ret_cx: Block<'blk, 'tcx>,
933 ret_debug_loc: DebugLoc) {
934 let _icx = push_ctxt("FunctionContext::finish");
936 self.build_return_block(ret_cx, ret_debug_loc);
938 DebugLoc::None.apply(self);
942 // Builds the return block for a function.
943 pub fn build_return_block(&self, ret_cx: Block<'blk, 'tcx>,
944 ret_debug_location: DebugLoc) {
945 if self.llretslotptr.get().is_none() ||
946 ret_cx.unreachable.get() ||
947 self.fn_ty.ret.is_indirect() {
948 return RetVoid(ret_cx, ret_debug_location);
951 let retslot = self.llretslotptr.get().unwrap();
952 let retptr = Value(retslot);
953 let llty = self.fn_ty.ret.original_ty;
954 match (retptr.get_dominating_store(ret_cx), self.fn_ty.ret.cast) {
955 // If there's only a single store to the ret slot, we can directly return
956 // the value that was stored and omit the store and the alloca.
957 // However, we only want to do this when there is no cast needed.
959 let mut retval = s.get_operand(0).unwrap().get();
960 s.erase_from_parent();
962 if retptr.has_no_uses() {
963 retptr.erase_from_parent();
966 if self.fn_ty.ret.is_indirect() {
967 Store(ret_cx, retval, get_param(self.llfn, 0));
968 RetVoid(ret_cx, ret_debug_location)
970 if llty == Type::i1(self.ccx) {
971 retval = Trunc(ret_cx, retval, llty);
973 Ret(ret_cx, retval, ret_debug_location)
976 (_, cast_ty) if self.fn_ty.ret.is_indirect() => {
977 // Otherwise, copy the return value to the ret slot.
978 assert_eq!(cast_ty, None);
979 let llsz = llsize_of(self.ccx, self.fn_ty.ret.ty);
980 let llalign = llalign_of_min(self.ccx, self.fn_ty.ret.ty);
981 call_memcpy(&B(ret_cx), get_param(self.llfn, 0),
982 retslot, llsz, llalign as u32);
983 RetVoid(ret_cx, ret_debug_location)
985 (_, Some(cast_ty)) => {
986 let load = Load(ret_cx, PointerCast(ret_cx, retslot, cast_ty.ptr_to()));
987 let llalign = llalign_of_min(self.ccx, self.fn_ty.ret.ty);
989 llvm::LLVMSetAlignment(load, llalign);
991 Ret(ret_cx, load, ret_debug_location)
994 let retval = if llty == Type::i1(self.ccx) {
995 let val = LoadRangeAssert(ret_cx, retslot, 0, 2, llvm::False);
996 Trunc(ret_cx, val, llty)
998 Load(ret_cx, retslot)
1000 Ret(ret_cx, retval, ret_debug_location)
1006 /// Builds an LLVM function out of a source function.
1008 /// If the function closes over its environment a closure will be returned.
1009 pub fn trans_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1011 instance: Instance<'tcx>,
1012 sig: &ty::FnSig<'tcx>,
1014 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1016 let _icx = push_ctxt("trans_closure");
1017 if !ccx.sess().no_landing_pads() {
1018 attributes::emit_uwtable(llfndecl, true);
1021 // this is an info! to allow collecting monomorphization statistics
1022 // and to allow finding the last function before LLVM aborts from
1024 info!("trans_closure(..., {})", instance);
1026 let fn_ty = FnType::new(ccx, abi, sig, &[]);
1028 let (arena, fcx): (TypedArena<_>, FunctionContext);
1029 arena = TypedArena::new();
1030 fcx = FunctionContext::new(ccx,
1033 Some((instance, sig, abi)),
1036 if fcx.mir.is_none() {
1037 bug!("attempted translation of `{}` w/o MIR", instance);
1040 mir::trans_mir(&fcx);
1043 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
1044 let _s = StatRecorder::new(ccx, ccx.tcx().item_path_str(instance.def));
1045 debug!("trans_instance(instance={:?})", instance);
1046 let _icx = push_ctxt("trans_instance");
1048 let fn_ty = ccx.tcx().lookup_item_type(instance.def).ty;
1049 let fn_ty = ccx.tcx().erase_regions(&fn_ty);
1050 let fn_ty = monomorphize::apply_param_substs(ccx.shared(), instance.substs, &fn_ty);
1052 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(fn_ty.fn_sig());
1053 let abi = fn_ty.fn_abi();
1055 let lldecl = match ccx.instances().borrow().get(&instance) {
1057 None => bug!("Instance `{:?}` not already declared", instance)
1060 trans_closure(ccx, lldecl, instance, &sig, abi);
1063 pub fn trans_ctor_shim<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1065 substs: &'tcx Substs<'tcx>,
1067 llfndecl: ValueRef) {
1068 attributes::inline(llfndecl, attributes::InlineAttr::Hint);
1069 attributes::set_frame_pointer_elimination(ccx, llfndecl);
1071 let ctor_ty = ccx.tcx().lookup_item_type(def_id).ty;
1072 let ctor_ty = monomorphize::apply_param_substs(ccx.shared(), substs, &ctor_ty);
1074 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&ctor_ty.fn_sig());
1075 let fn_ty = FnType::new(ccx, Abi::Rust, &sig, &[]);
1077 let (arena, fcx): (TypedArena<_>, FunctionContext);
1078 arena = TypedArena::new();
1079 fcx = FunctionContext::new(ccx, llfndecl, fn_ty, None, &arena);
1080 let bcx = fcx.init(false);
1082 if !fcx.fn_ty.ret.is_ignore() {
1083 let dest = fcx.llretslotptr.get().unwrap();
1084 let dest_val = adt::MaybeSizedValue::sized(dest); // Can return unsized value
1085 let mut llarg_idx = fcx.fn_ty.ret.is_indirect() as usize;
1086 let mut arg_idx = 0;
1087 for (i, arg_ty) in sig.inputs.into_iter().enumerate() {
1088 let lldestptr = adt::trans_field_ptr(bcx, sig.output, dest_val, Disr::from(disr), i);
1089 let arg = &fcx.fn_ty.args[arg_idx];
1091 let b = &bcx.build();
1092 if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
1093 let meta = &fcx.fn_ty.args[arg_idx];
1095 arg.store_fn_arg(b, &mut llarg_idx, get_dataptr(bcx, lldestptr));
1096 meta.store_fn_arg(b, &mut llarg_idx, get_meta(bcx, lldestptr));
1098 arg.store_fn_arg(b, &mut llarg_idx, lldestptr);
1101 adt::trans_set_discr(bcx, sig.output, dest, disr);
1104 fcx.finish(bcx, DebugLoc::None);
1107 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
1108 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1109 // applicable to variable declarations and may not really make sense for
1110 // Rust code in the first place but whitelist them anyway and trust that
1111 // the user knows what s/he's doing. Who knows, unanticipated use cases
1112 // may pop up in the future.
1114 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1115 // and don't have to be, LLVM treats them as no-ops.
1117 "appending" => Some(llvm::Linkage::AppendingLinkage),
1118 "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
1119 "common" => Some(llvm::Linkage::CommonLinkage),
1120 "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
1121 "external" => Some(llvm::Linkage::ExternalLinkage),
1122 "internal" => Some(llvm::Linkage::InternalLinkage),
1123 "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
1124 "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
1125 "private" => Some(llvm::Linkage::PrivateLinkage),
1126 "weak" => Some(llvm::Linkage::WeakAnyLinkage),
1127 "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
1132 pub fn set_link_section(ccx: &CrateContext,
1134 attrs: &[ast::Attribute]) {
1135 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
1136 if contains_null(§) {
1137 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
1140 let buf = CString::new(sect.as_bytes()).unwrap();
1141 llvm::LLVMSetSection(llval, buf.as_ptr());
1146 /// Create the `main` function which will initialise the rust runtime and call
1147 /// users’ main function.
1148 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
1149 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
1150 Some((id, span)) => {
1151 (ccx.tcx().map.local_def_id(id), span)
1156 // check for the #[rustc_error] annotation, which forces an
1157 // error in trans. This is used to write compile-fail tests
1158 // that actually test that compilation succeeds without
1159 // reporting an error.
1160 if ccx.tcx().has_attr(main_def_id, "rustc_error") {
1161 ccx.tcx().sess.span_fatal(span, "compilation successful");
1164 let instance = Instance::mono(ccx.shared(), main_def_id);
1166 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
1167 // We want to create the wrapper in the same codegen unit as Rust's main
1172 let main_llfn = Callee::def(ccx, main_def_id, instance.substs).reify(ccx);
1174 let et = ccx.sess().entry_type.get().unwrap();
1176 config::EntryMain => {
1177 create_entry_fn(ccx, span, main_llfn, true);
1179 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
1180 config::EntryNone => {} // Do nothing.
1183 fn create_entry_fn(ccx: &CrateContext,
1185 rust_main: ValueRef,
1186 use_start_lang_item: bool) {
1187 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
1189 if declare::get_defined_value(ccx, "main").is_some() {
1190 // FIXME: We should be smart and show a better diagnostic here.
1191 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
1192 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
1194 ccx.sess().abort_if_errors();
1197 let llfn = declare::declare_cfn(ccx, "main", llfty);
1200 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, "top\0".as_ptr() as *const _)
1202 let bld = ccx.raw_builder();
1204 llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1206 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
1208 let (start_fn, args) = if use_start_lang_item {
1209 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
1211 Err(s) => ccx.sess().fatal(&s)
1213 let empty_substs = ccx.tcx().intern_substs(&[]);
1214 let start_fn = Callee::def(ccx, start_def_id, empty_substs).reify(ccx);
1216 let opaque_rust_main =
1217 llvm::LLVMBuildPointerCast(bld,
1219 Type::i8p(ccx).to_ref(),
1220 "rust_main\0".as_ptr() as *const _);
1222 vec![opaque_rust_main, get_param(llfn, 0), get_param(llfn, 1)]
1226 debug!("using user-defined start fn");
1227 let args = vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)];
1232 let result = llvm::LLVMRustBuildCall(bld,
1235 args.len() as c_uint,
1239 llvm::LLVMBuildRet(bld, result);
1244 fn contains_null(s: &str) -> bool {
1245 s.bytes().any(|b| b == 0)
1248 fn write_metadata(cx: &SharedCrateContext,
1249 reachable_ids: &NodeSet) -> Vec<u8> {
1252 #[derive(PartialEq, Eq, PartialOrd, Ord)]
1259 let kind = cx.sess().crate_types.borrow().iter().map(|ty| {
1261 config::CrateTypeExecutable |
1262 config::CrateTypeStaticlib |
1263 config::CrateTypeCdylib => MetadataKind::None,
1265 config::CrateTypeRlib => MetadataKind::Uncompressed,
1267 config::CrateTypeDylib |
1268 config::CrateTypeProcMacro => MetadataKind::Compressed,
1272 if kind == MetadataKind::None {
1276 let cstore = &cx.tcx().sess.cstore;
1277 let metadata = cstore.encode_metadata(cx.tcx(),
1281 if kind == MetadataKind::Uncompressed {
1285 assert!(kind == MetadataKind::Compressed);
1286 let mut compressed = cstore.metadata_encoding_version().to_vec();
1287 compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
1289 let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
1290 let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
1291 let name = cx.metadata_symbol_name();
1292 let buf = CString::new(name).unwrap();
1293 let llglobal = unsafe {
1294 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
1297 llvm::LLVMSetInitializer(llglobal, llconst);
1299 cx.tcx().sess.cstore.metadata_section_name(&cx.sess().target.target);
1300 let name = CString::new(section_name).unwrap();
1301 llvm::LLVMSetSection(llglobal, name.as_ptr());
1303 // Also generate a .section directive to force no
1304 // flags, at least for ELF outputs, so that the
1305 // metadata doesn't get loaded into memory.
1306 let directive = format!(".section {}", section_name);
1307 let directive = CString::new(directive).unwrap();
1308 llvm::LLVMSetModuleInlineAsm(cx.metadata_llmod(), directive.as_ptr())
1313 /// Find any symbols that are defined in one compilation unit, but not declared
1314 /// in any other compilation unit. Give these symbols internal linkage.
1315 fn internalize_symbols<'a, 'tcx>(sess: &Session,
1316 ccxs: &CrateContextList<'a, 'tcx>,
1317 symbol_map: &SymbolMap<'tcx>,
1318 reachable: &FnvHashSet<&str>) {
1319 let scx = ccxs.shared();
1320 let tcx = scx.tcx();
1322 // In incr. comp. mode, we can't necessarily see all refs since we
1323 // don't generate LLVM IR for reused modules, so skip this
1324 // step. Later we should get smarter.
1325 if sess.opts.debugging_opts.incremental.is_some() {
1329 // 'unsafe' because we are holding on to CStr's from the LLVM module within
1332 let mut referenced_somewhere = FnvHashSet();
1334 // Collect all symbols that need to stay externally visible because they
1335 // are referenced via a declaration in some other codegen unit.
1336 for ccx in ccxs.iter_need_trans() {
1337 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
1338 let linkage = llvm::LLVMRustGetLinkage(val);
1339 // We only care about external declarations (not definitions)
1340 // and available_externally definitions.
1341 let is_available_externally = linkage == llvm::Linkage::AvailableExternallyLinkage;
1342 let is_decl = llvm::LLVMIsDeclaration(val) != 0;
1344 if is_decl || is_available_externally {
1345 let symbol_name = CStr::from_ptr(llvm::LLVMGetValueName(val));
1346 referenced_somewhere.insert(symbol_name);
1351 // Also collect all symbols for which we cannot adjust linkage, because
1352 // it is fixed by some directive in the source code (e.g. #[no_mangle]).
1353 let linkage_fixed_explicitly: FnvHashSet<_> = scx
1354 .translation_items()
1358 .filter(|trans_item|{
1359 trans_item.explicit_linkage(tcx).is_some()
1361 .map(|trans_item| symbol_map.get_or_compute(scx, trans_item))
1364 // Examine each external definition. If the definition is not used in
1365 // any other compilation unit, and is not reachable from other crates,
1366 // then give it internal linkage.
1367 for ccx in ccxs.iter_need_trans() {
1368 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
1369 let linkage = llvm::LLVMRustGetLinkage(val);
1371 let is_externally_visible = (linkage == llvm::Linkage::ExternalLinkage) ||
1372 (linkage == llvm::Linkage::LinkOnceODRLinkage) ||
1373 (linkage == llvm::Linkage::WeakODRLinkage);
1374 let is_definition = llvm::LLVMIsDeclaration(val) == 0;
1376 // If this is a definition (as opposed to just a declaration)
1377 // and externally visible, check if we can internalize it
1378 if is_definition && is_externally_visible {
1379 let name_cstr = CStr::from_ptr(llvm::LLVMGetValueName(val));
1380 let name_str = name_cstr.to_str().unwrap();
1381 let name_cow = Cow::Borrowed(name_str);
1383 let is_referenced_somewhere = referenced_somewhere.contains(&name_cstr);
1384 let is_reachable = reachable.contains(&name_str);
1385 let has_fixed_linkage = linkage_fixed_explicitly.contains(&name_cow);
1387 if !is_referenced_somewhere && !is_reachable && !has_fixed_linkage {
1388 llvm::LLVMRustSetLinkage(val, llvm::Linkage::InternalLinkage);
1389 llvm::LLVMSetDLLStorageClass(val,
1390 llvm::DLLStorageClass::Default);
1391 llvm::UnsetComdat(val);
1399 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1400 // This is required to satisfy `dllimport` references to static data in .rlibs
1401 // when using MSVC linker. We do this only for data, as linker can fix up
1402 // code references on its own.
1403 // See #26591, #27438
1404 fn create_imps(cx: &CrateContextList) {
1405 // The x86 ABI seems to require that leading underscores are added to symbol
1406 // names, so we need an extra underscore on 32-bit. There's also a leading
1407 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
1408 // underscores added in front).
1409 let prefix = if cx.shared().sess().target.target.target_pointer_width == "32" {
1415 for ccx in cx.iter_need_trans() {
1416 let exported: Vec<_> = iter_globals(ccx.llmod())
1418 llvm::LLVMRustGetLinkage(val) ==
1419 llvm::Linkage::ExternalLinkage &&
1420 llvm::LLVMIsDeclaration(val) == 0
1424 let i8p_ty = Type::i8p(&ccx);
1425 for val in exported {
1426 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
1427 let mut imp_name = prefix.as_bytes().to_vec();
1428 imp_name.extend(name.to_bytes());
1429 let imp_name = CString::new(imp_name).unwrap();
1430 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
1432 imp_name.as_ptr() as *const _);
1433 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
1434 llvm::LLVMSetInitializer(imp, init);
1435 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1443 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
1446 impl Iterator for ValueIter {
1447 type Item = ValueRef;
1449 fn next(&mut self) -> Option<ValueRef> {
1452 self.cur = unsafe { (self.step)(old) };
1460 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
1463 cur: llvm::LLVMGetFirstGlobal(llmod),
1464 step: llvm::LLVMGetNextGlobal,
1469 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
1472 cur: llvm::LLVMGetFirstFunction(llmod),
1473 step: llvm::LLVMGetNextFunction,
1478 /// The context provided lists a set of reachable ids as calculated by
1479 /// middle::reachable, but this contains far more ids and symbols than we're
1480 /// actually exposing from the object file. This function will filter the set in
1481 /// the context to the set of ids which correspond to symbols that are exposed
1482 /// from the object file being generated.
1484 /// This list is later used by linkers to determine the set of symbols needed to
1485 /// be exposed from a dynamic library and it's also encoded into the metadata.
1486 pub fn filter_reachable_ids(tcx: TyCtxt, reachable: NodeSet) -> NodeSet {
1487 reachable.into_iter().filter(|&id| {
1488 // Next, we want to ignore some FFI functions that are not exposed from
1489 // this crate. Reachable FFI functions can be lumped into two
1492 // 1. Those that are included statically via a static library
1493 // 2. Those included otherwise (e.g. dynamically or via a framework)
1495 // Although our LLVM module is not literally emitting code for the
1496 // statically included symbols, it's an export of our library which
1497 // needs to be passed on to the linker and encoded in the metadata.
1499 // As a result, if this id is an FFI item (foreign item) then we only
1500 // let it through if it's included statically.
1501 match tcx.map.get(id) {
1502 hir_map::NodeForeignItem(..) => {
1503 tcx.sess.cstore.is_statically_included_foreign_item(id)
1506 // Only consider nodes that actually have exported symbols.
1507 hir_map::NodeItem(&hir::Item {
1508 node: hir::ItemStatic(..), .. }) |
1509 hir_map::NodeItem(&hir::Item {
1510 node: hir::ItemFn(..), .. }) |
1511 hir_map::NodeImplItem(&hir::ImplItem {
1512 node: hir::ImplItemKind::Method(..), .. }) => {
1513 let def_id = tcx.map.local_def_id(id);
1514 let generics = tcx.lookup_generics(def_id);
1515 let attributes = tcx.get_attrs(def_id);
1516 (generics.parent_types == 0 && generics.types.is_empty()) &&
1517 // Functions marked with #[inline] are only ever translated
1518 // with "internal" linkage and are never exported.
1519 !attr::requests_inline(&attributes[..])
1527 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1528 analysis: ty::CrateAnalysis,
1529 incremental_hashes_map: &IncrementalHashesMap)
1530 -> CrateTranslation {
1531 let _task = tcx.dep_graph.in_task(DepNode::TransCrate);
1533 // Be careful with this krate: obviously it gives access to the
1534 // entire contents of the krate. So if you push any subtasks of
1535 // `TransCrate`, you need to be careful to register "reads" of the
1536 // particular items that will be processed.
1537 let krate = tcx.map.krate();
1539 let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
1540 let reachable = filter_reachable_ids(tcx, reachable);
1542 let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
1545 tcx.sess.opts.debug_assertions
1548 let link_meta = link::build_link_meta(incremental_hashes_map, name);
1550 let shared_ccx = SharedCrateContext::new(tcx,
1555 // Translate the metadata.
1556 let metadata = time(tcx.sess.time_passes(), "write metadata", || {
1557 write_metadata(&shared_ccx, shared_ccx.reachable())
1560 let metadata_module = ModuleTranslation {
1561 name: "metadata".to_string(),
1562 symbol_name_hash: 0, // we always rebuild metadata, at least for now
1563 source: ModuleSource::Translated(ModuleLlvm {
1564 llcx: shared_ccx.metadata_llcx(),
1565 llmod: shared_ccx.metadata_llmod(),
1568 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
1570 // Run the translation item collector and partition the collected items into
1572 let (codegen_units, symbol_map) = collect_and_partition_translation_items(&shared_ccx);
1574 let symbol_map = Rc::new(symbol_map);
1576 let previous_work_products = trans_reuse_previous_work_products(tcx,
1580 let crate_context_list = CrateContextList::new(&shared_ccx,
1582 previous_work_products,
1583 symbol_map.clone());
1584 let modules: Vec<_> = crate_context_list.iter_all()
1586 let source = match ccx.previous_work_product() {
1587 Some(buf) => ModuleSource::Preexisting(buf.clone()),
1588 None => ModuleSource::Translated(ModuleLlvm {
1595 name: String::from(ccx.codegen_unit().name()),
1596 symbol_name_hash: ccx.codegen_unit().compute_symbol_name_hash(tcx, &symbol_map),
1602 assert_module_sources::assert_module_sources(tcx, &modules);
1604 // Skip crate items and just output metadata in -Z no-trans mode.
1605 if tcx.sess.opts.debugging_opts.no_trans {
1606 let linker_info = LinkerInfo::new(&shared_ccx, &[]);
1607 return CrateTranslation {
1609 metadata_module: metadata_module,
1613 no_builtins: no_builtins,
1614 linker_info: linker_info
1618 // Instantiate translation items without filling out definitions yet...
1619 for ccx in crate_context_list.iter_need_trans() {
1620 let cgu = ccx.codegen_unit();
1621 let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
1623 tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
1624 for (trans_item, linkage) in trans_items {
1625 trans_item.predefine(&ccx, linkage);
1630 // ... and now that we have everything pre-defined, fill out those definitions.
1631 for ccx in crate_context_list.iter_need_trans() {
1632 let cgu = ccx.codegen_unit();
1633 let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
1634 tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
1635 for (trans_item, _) in trans_items {
1636 trans_item.define(&ccx);
1639 // If this codegen unit contains the main function, also create the
1641 maybe_create_entry_wrapper(&ccx);
1643 // Run replace-all-uses-with for statics that need it
1644 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1646 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1647 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1648 llvm::LLVMDeleteGlobal(old_g);
1652 // Finalize debuginfo
1653 if ccx.sess().opts.debuginfo != NoDebugInfo {
1654 debuginfo::finalize(&ccx);
1659 symbol_names_test::report_symbol_names(&shared_ccx);
1661 if shared_ccx.sess().trans_stats() {
1662 let stats = shared_ccx.stats();
1663 println!("--- trans stats ---");
1664 println!("n_glues_created: {}", stats.n_glues_created.get());
1665 println!("n_null_glues: {}", stats.n_null_glues.get());
1666 println!("n_real_glues: {}", stats.n_real_glues.get());
1668 println!("n_fns: {}", stats.n_fns.get());
1669 println!("n_inlines: {}", stats.n_inlines.get());
1670 println!("n_closures: {}", stats.n_closures.get());
1671 println!("fn stats:");
1672 stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1673 insns_b.cmp(&insns_a)
1675 for tuple in stats.fn_stats.borrow().iter() {
1677 (ref name, insns) => {
1678 println!("{} insns, {}", insns, *name);
1684 if shared_ccx.sess().count_llvm_insns() {
1685 for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
1686 println!("{:7} {}", *v, *k);
1690 let sess = shared_ccx.sess();
1691 let mut reachable_symbols = shared_ccx.reachable().iter().map(|&id| {
1692 let def_id = shared_ccx.tcx().map.local_def_id(id);
1693 symbol_for_def_id(def_id, &shared_ccx, &symbol_map)
1694 }).collect::<Vec<_>>();
1696 if sess.entry_fn.borrow().is_some() {
1697 reachable_symbols.push("main".to_string());
1700 if sess.crate_types.borrow().contains(&config::CrateTypeDylib) {
1701 reachable_symbols.push(shared_ccx.metadata_symbol_name());
1704 // For the purposes of LTO or when creating a cdylib, we add to the
1705 // reachable set all of the upstream reachable extern fns. These functions
1706 // are all part of the public ABI of the final product, so we need to
1709 // Note that this happens even if LTO isn't requested or we're not creating
1710 // a cdylib. In those cases, though, we're not even reading the
1711 // `reachable_symbols` list later on so it should be ok.
1712 for cnum in sess.cstore.crates() {
1713 let syms = sess.cstore.reachable_ids(cnum);
1714 reachable_symbols.extend(syms.into_iter().filter(|&def_id| {
1715 let applicable = match sess.cstore.describe_def(def_id) {
1716 Some(Def::Static(..)) => true,
1717 Some(Def::Fn(_)) => {
1718 shared_ccx.tcx().lookup_generics(def_id).types.is_empty()
1724 let attrs = shared_ccx.tcx().get_attrs(def_id);
1725 attr::contains_extern_indicator(sess.diagnostic(), &attrs)
1730 symbol_for_def_id(did, &shared_ccx, &symbol_map)
1734 time(shared_ccx.sess().time_passes(), "internalize symbols", || {
1735 internalize_symbols(sess,
1736 &crate_context_list,
1738 &reachable_symbols.iter()
1743 if sess.target.target.options.is_like_msvc &&
1744 sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1745 create_imps(&crate_context_list);
1748 let linker_info = LinkerInfo::new(&shared_ccx, &reachable_symbols);
1752 metadata_module: metadata_module,
1755 reachable: reachable_symbols,
1756 no_builtins: no_builtins,
1757 linker_info: linker_info
1761 /// For each CGU, identify if we can reuse an existing object file (or
1762 /// maybe other context).
1763 fn trans_reuse_previous_work_products(tcx: TyCtxt,
1764 codegen_units: &[CodegenUnit],
1765 symbol_map: &SymbolMap)
1766 -> Vec<Option<WorkProduct>> {
1767 debug!("trans_reuse_previous_work_products()");
1771 let id = cgu.work_product_id();
1773 let hash = cgu.compute_symbol_name_hash(tcx, symbol_map);
1775 debug!("trans_reuse_previous_work_products: id={:?} hash={}", id, hash);
1777 if let Some(work_product) = tcx.dep_graph.previous_work_product(&id) {
1778 if work_product.input_hash == hash {
1779 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1780 return Some(work_product);
1782 debug!("trans_reuse_previous_work_products: \
1783 not reusing {:?} because hash changed to {:?}",
1784 work_product, hash);
1793 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>)
1794 -> (Vec<CodegenUnit<'tcx>>, SymbolMap<'tcx>) {
1795 let time_passes = scx.sess().time_passes();
1797 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1799 let mode_string = s.to_lowercase();
1800 let mode_string = mode_string.trim();
1801 if mode_string == "eager" {
1802 TransItemCollectionMode::Eager
1804 if mode_string != "lazy" {
1805 let message = format!("Unknown codegen-item collection mode '{}'. \
1806 Falling back to 'lazy' mode.",
1808 scx.sess().warn(&message);
1811 TransItemCollectionMode::Lazy
1814 None => TransItemCollectionMode::Lazy
1817 let (items, inlining_map) =
1818 time(time_passes, "translation item collection", || {
1819 collector::collect_crate_translation_items(&scx, collection_mode)
1822 let symbol_map = SymbolMap::build(scx, items.iter().cloned());
1824 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1825 PartitioningStrategy::PerModule
1827 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1830 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1831 partitioning::partition(scx,
1832 items.iter().cloned(),
1837 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1838 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1841 let mut ccx_map = scx.translation_items().borrow_mut();
1843 for trans_item in items.iter().cloned() {
1844 ccx_map.insert(trans_item);
1848 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1849 let mut item_to_cgus = FnvHashMap();
1851 for cgu in &codegen_units {
1852 for (&trans_item, &linkage) in cgu.items() {
1853 item_to_cgus.entry(trans_item)
1854 .or_insert(Vec::new())
1855 .push((cgu.name().clone(), linkage));
1859 let mut item_keys: Vec<_> = items
1862 let mut output = i.to_string(scx.tcx());
1863 output.push_str(" @@");
1864 let mut empty = Vec::new();
1865 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1866 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1868 for &(ref cgu_name, linkage) in cgus.iter() {
1869 output.push_str(" ");
1870 output.push_str(&cgu_name[..]);
1872 let linkage_abbrev = match linkage {
1873 llvm::Linkage::ExternalLinkage => "External",
1874 llvm::Linkage::AvailableExternallyLinkage => "Available",
1875 llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1876 llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1877 llvm::Linkage::WeakAnyLinkage => "WeakAny",
1878 llvm::Linkage::WeakODRLinkage => "WeakODR",
1879 llvm::Linkage::AppendingLinkage => "Appending",
1880 llvm::Linkage::InternalLinkage => "Internal",
1881 llvm::Linkage::PrivateLinkage => "Private",
1882 llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1883 llvm::Linkage::CommonLinkage => "Common",
1886 output.push_str("[");
1887 output.push_str(linkage_abbrev);
1888 output.push_str("]");
1896 for item in item_keys {
1897 println!("TRANS_ITEM {}", item);
1901 (codegen_units, symbol_map)
1904 fn symbol_for_def_id<'a, 'tcx>(def_id: DefId,
1905 scx: &SharedCrateContext<'a, 'tcx>,
1906 symbol_map: &SymbolMap<'tcx>)
1908 // Just try to look things up in the symbol map. If nothing's there, we
1910 if let Some(node_id) = scx.tcx().map.as_local_node_id(def_id) {
1911 if let Some(sym) = symbol_map.get(TransItem::Static(node_id)) {
1912 return sym.to_owned();
1916 let instance = Instance::mono(scx, def_id);
1918 symbol_map.get(TransItem::Fn(instance))
1920 .unwrap_or_else(|| instance.symbol_name(scx))