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 use super::CrateTranslation;
27 use super::ModuleLlvm;
28 use super::ModuleSource;
29 use super::ModuleTranslation;
31 use assert_module_sources;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use llvm::{Linkage, ValueRef, Vector, get_param};
37 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
38 use middle::lang_items::StartFnLangItem;
39 use rustc::ty::subst::Substs;
41 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
42 use rustc::ty::adjustment::CustomCoerceUnsized;
43 use rustc::dep_graph::{DepNode, WorkProduct};
44 use rustc::hir::map as hir_map;
45 use rustc::util::common::time;
46 use session::config::{self, NoDebugInfo};
47 use rustc_incremental::IncrementalHashesMap;
48 use session::{self, DataTypeKind, Session};
49 use abi::{self, Abi, FnType};
54 use common::{BlockAndBuilder, C_bool, C_bytes_in_context, C_i32, C_uint};
55 use collector::{self, TransItemCollectionMode};
56 use common::{C_struct_in_context, C_u64, C_undef};
57 use common::{CrateContext, FunctionContext};
58 use common::{fulfill_obligation};
59 use common::{type_is_zero_size, val_ty};
62 use context::{SharedCrateContext, CrateContextList};
66 use machine::{llalign_of_min, llsize_of};
69 use monomorphize::{self, Instance};
70 use partitioning::{self, PartitioningStrategy, CodegenUnit};
71 use symbol_map::SymbolMap;
72 use symbol_names_test;
73 use trans_item::{TransItem, DefPathBasedNames};
78 use util::nodemap::{NodeSet, FxHashMap, FxHashSet};
81 use std::ffi::{CStr, CString};
85 use syntax_pos::{Span, DUMMY_SP};
88 use rustc::ty::layout::{self, Layout};
91 pub struct StatRecorder<'a, 'tcx: 'a> {
92 ccx: &'a CrateContext<'a, 'tcx>,
97 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
98 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
99 let istart = ccx.stats().n_llvm_insns.get();
108 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
110 if self.ccx.sess().trans_stats() {
111 let iend = self.ccx.stats().n_llvm_insns.get();
112 self.ccx.stats().fn_stats.borrow_mut()
113 .push((self.name.take().unwrap(), iend - self.istart));
114 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
115 // Reset LLVM insn count to avoid compound costs.
116 self.ccx.stats().n_llvm_insns.set(self.istart);
121 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
122 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
125 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
126 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
129 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
131 -> llvm::IntPredicate {
133 hir::BiEq => llvm::IntEQ,
134 hir::BiNe => llvm::IntNE,
135 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
136 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
137 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
138 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
140 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
147 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
149 hir::BiEq => llvm::RealOEQ,
150 hir::BiNe => llvm::RealUNE,
151 hir::BiLt => llvm::RealOLT,
152 hir::BiLe => llvm::RealOLE,
153 hir::BiGt => llvm::RealOGT,
154 hir::BiGe => llvm::RealOGE,
156 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
163 pub fn compare_simd_types<'a, 'tcx>(
164 bcx: &BlockAndBuilder<'a, 'tcx>,
171 let signed = match t.sty {
173 let cmp = bin_op_to_fcmp_predicate(op);
174 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
176 ty::TyUint(_) => false,
177 ty::TyInt(_) => true,
178 _ => bug!("compare_simd_types: invalid SIMD type"),
181 let cmp = bin_op_to_icmp_predicate(op, signed);
182 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
183 // to get the correctly sized type. This will compile to a single instruction
184 // once the IR is converted to assembly if the SIMD instruction is supported
185 // by the target architecture.
186 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
189 /// Retrieve the information we are losing (making dynamic) in an unsizing
192 /// The `old_info` argument is a bit funny. It is intended for use
193 /// in an upcast, where the new vtable for an object will be drived
194 /// from the old one.
195 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
198 old_info: Option<ValueRef>)
200 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
201 match (&source.sty, &target.sty) {
202 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
203 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
204 // For now, upcasts are limited to changes in marker
205 // traits, and hence never actually require an actual
206 // change to the vtable.
207 old_info.expect("unsized_info: missing old info for trait upcast")
209 (_, &ty::TyDynamic(ref data, ..)) => {
210 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
211 Type::vtable_ptr(ccx))
213 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
219 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
220 pub fn unsize_thin_ptr<'a, 'tcx>(
221 bcx: &BlockAndBuilder<'a, 'tcx>,
225 ) -> (ValueRef, ValueRef) {
226 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
227 match (&src_ty.sty, &dst_ty.sty) {
228 (&ty::TyBox(a), &ty::TyBox(b)) |
229 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
230 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
231 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
232 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
233 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
234 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
235 assert!(bcx.ccx.shared().type_is_sized(a));
236 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
237 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
239 _ => bug!("unsize_thin_ptr: called on bad types"),
243 /// Coerce `src`, which is a reference to a value of type `src_ty`,
244 /// to a value of type `dst_ty` and store the result in `dst`
245 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &BlockAndBuilder<'a, 'tcx>,
250 match (&src_ty.sty, &dst_ty.sty) {
251 (&ty::TyBox(..), &ty::TyBox(..)) |
252 (&ty::TyRef(..), &ty::TyRef(..)) |
253 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
254 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
255 let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
256 // fat-ptr to fat-ptr unsize preserves the vtable
257 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
258 // So we need to pointercast the base to ensure
259 // the types match up.
260 let (base, info) = load_fat_ptr(bcx, src, src_ty);
261 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
262 let base = bcx.pointercast(base, llcast_ty);
265 let base = load_ty(bcx, src, src_ty);
266 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
268 store_fat_ptr(bcx, base, info, dst, dst_ty);
271 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
272 assert_eq!(def_a, def_b);
274 let src_fields = def_a.variants[0].fields.iter().map(|f| {
275 monomorphize::field_ty(bcx.tcx(), substs_a, f)
277 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
278 monomorphize::field_ty(bcx.tcx(), substs_b, f)
281 let src = adt::MaybeSizedValue::sized(src);
282 let dst = adt::MaybeSizedValue::sized(dst);
284 let iter = src_fields.zip(dst_fields).enumerate();
285 for (i, (src_fty, dst_fty)) in iter {
286 if type_is_zero_size(bcx.ccx, dst_fty) {
290 let src_f = adt::trans_field_ptr(bcx, src_ty, src, Disr(0), i);
291 let dst_f = adt::trans_field_ptr(bcx, dst_ty, dst, Disr(0), i);
292 if src_fty == dst_fty {
293 memcpy_ty(bcx, dst_f, src_f, src_fty);
295 coerce_unsized_into(bcx, src_f, src_fty, dst_f, dst_fty);
299 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
305 pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>,
308 -> CustomCoerceUnsized {
309 let trait_ref = ty::Binder(ty::TraitRef {
310 def_id: scx.tcx().lang_items.coerce_unsized_trait().unwrap(),
311 substs: scx.tcx().mk_substs_trait(source_ty, &[target_ty])
314 match fulfill_obligation(scx, DUMMY_SP, trait_ref) {
315 traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
316 scx.tcx().custom_coerce_unsized_kind(impl_def_id)
319 bug!("invalid CoerceUnsized vtable: {:?}", vtable);
324 pub fn cast_shift_expr_rhs(
325 cx: &BlockAndBuilder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
327 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
330 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
334 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
335 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
338 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
344 where F: FnOnce(ValueRef, Type) -> ValueRef,
345 G: FnOnce(ValueRef, Type) -> ValueRef
347 // Shifts may have any size int on the rhs
349 let mut rhs_llty = val_ty(rhs);
350 let mut lhs_llty = val_ty(lhs);
351 if rhs_llty.kind() == Vector {
352 rhs_llty = rhs_llty.element_type()
354 if lhs_llty.kind() == Vector {
355 lhs_llty = lhs_llty.element_type()
357 let rhs_sz = rhs_llty.int_width();
358 let lhs_sz = lhs_llty.int_width();
361 } else if lhs_sz > rhs_sz {
362 // FIXME (#1877: If shifting by negative
363 // values becomes not undefined then this is wrong.
373 /// Returns whether this session's target will use SEH-based unwinding.
375 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
376 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
377 /// 64-bit MinGW) instead of "full SEH".
378 pub fn wants_msvc_seh(sess: &Session) -> bool {
379 sess.target.target.options.is_like_msvc
382 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
383 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
384 b.call(assume_intrinsic, &[val], None);
387 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
388 /// differs from the type used for SSA values. Also handles various special cases where the type
389 /// gives us better information about what we are loading.
390 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
392 if type_is_zero_size(ccx, t) {
393 return C_undef(type_of::type_of(ccx, t));
397 let global = llvm::LLVMIsAGlobalVariable(ptr);
398 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
399 let val = llvm::LLVMGetInitializer(global);
402 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
410 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False), Type::i1(ccx))
411 } else if t.is_char() {
412 // a char is a Unicode codepoint, and so takes values from 0
413 // to 0x10FFFF inclusive only.
414 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False)
415 } else if (t.is_region_ptr() || t.is_unique()) && !common::type_is_fat_ptr(ccx, t) {
422 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
423 /// differs from the type used for SSA values.
424 pub fn store_ty<'a, 'tcx>(cx: &BlockAndBuilder<'a, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
425 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
427 if common::type_is_fat_ptr(cx.ccx, t) {
428 let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
429 let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
430 store_fat_ptr(cx, lladdr, llextra, dst, t);
432 cx.store(from_immediate(cx, v), dst);
436 pub fn store_fat_ptr<'a, 'tcx>(cx: &BlockAndBuilder<'a, 'tcx>,
441 // FIXME: emit metadata
442 cx.store(data, get_dataptr(cx, dst));
443 cx.store(extra, get_meta(cx, dst));
446 pub fn load_fat_ptr<'a, 'tcx>(
447 b: &Builder<'a, 'tcx>, src: ValueRef, t: Ty<'tcx>
448 ) -> (ValueRef, ValueRef) {
449 let ptr = get_dataptr(b, src);
450 let ptr = if t.is_region_ptr() || t.is_unique() {
456 // FIXME: emit metadata on `meta`.
457 let meta = b.load(get_meta(b, src));
462 pub fn from_immediate(bcx: &BlockAndBuilder, val: ValueRef) -> ValueRef {
463 if val_ty(val) == Type::i1(bcx.ccx) {
464 bcx.zext(val, Type::i8(bcx.ccx))
470 pub fn to_immediate(bcx: &BlockAndBuilder, val: ValueRef, ty: Ty) -> ValueRef {
472 bcx.trunc(val, Type::i1(bcx.ccx))
478 pub enum Lifetime { Start, End }
481 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
482 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
483 // and the intrinsic for `lt` and passes them to `emit`, which is in
484 // charge of generating code to call the passed intrinsic on whatever
485 // block of generated code is targetted for the intrinsic.
487 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
488 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
489 pub fn call(self, b: &Builder, ptr: ValueRef) {
490 if b.ccx.sess().opts.optimize == config::OptLevel::No {
494 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
499 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
500 Lifetime::Start => "llvm.lifetime.start",
501 Lifetime::End => "llvm.lifetime.end"
504 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
505 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
509 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
515 let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
516 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
517 let memcpy = ccx.get_intrinsic(&key);
518 let src_ptr = b.pointercast(src, Type::i8p(ccx));
519 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
520 let size = b.intcast(n_bytes, ccx.int_type());
521 let align = C_i32(ccx, align as i32);
522 let volatile = C_bool(ccx, false);
523 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
526 pub fn memcpy_ty<'a, 'tcx>(
527 bcx: &BlockAndBuilder<'a, 'tcx>, dst: ValueRef, src: ValueRef, t: Ty<'tcx>
531 if type_is_zero_size(ccx, t) {
535 if t.is_structural() {
536 let llty = type_of::type_of(ccx, t);
537 let llsz = llsize_of(ccx, llty);
538 let llalign = type_of::align_of(ccx, t);
539 call_memcpy(bcx, dst, src, llsz, llalign as u32);
540 } else if common::type_is_fat_ptr(bcx.ccx, t) {
541 let (data, extra) = load_fat_ptr(bcx, src, t);
542 store_fat_ptr(bcx, data, extra, dst, t);
544 store_ty(bcx, load_ty(bcx, src, t), dst, t);
548 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
553 volatile: bool) -> ValueRef {
554 let ptr_width = &b.ccx.sess().target.target.target_pointer_width[..];
555 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
556 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
557 let volatile = C_bool(b.ccx, volatile);
558 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
561 pub fn alloc_ty<'a, 'tcx>(bcx: &BlockAndBuilder<'a, 'tcx>, ty: Ty<'tcx>, name: &str) -> ValueRef {
562 assert!(!ty.has_param_types());
563 bcx.fcx().alloca(type_of::type_of(bcx.ccx, ty), name)
566 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
567 let _s = if ccx.sess().trans_stats() {
568 let mut instance_name = String::new();
569 DefPathBasedNames::new(ccx.tcx(), true, true)
570 .push_def_path(instance.def, &mut instance_name);
571 Some(StatRecorder::new(ccx, instance_name))
576 // this is an info! to allow collecting monomorphization statistics
577 // and to allow finding the last function before LLVM aborts from
579 info!("trans_instance({})", instance);
581 let fn_ty = ccx.tcx().item_type(instance.def);
582 let fn_ty = ccx.tcx().erase_regions(&fn_ty);
583 let fn_ty = monomorphize::apply_param_substs(ccx.shared(), instance.substs, &fn_ty);
585 let ty::BareFnTy { abi, ref sig, .. } = *common::ty_fn_ty(ccx, fn_ty);
586 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(sig);
588 let lldecl = match ccx.instances().borrow().get(&instance) {
590 None => bug!("Instance `{:?}` not already declared", instance)
593 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
595 if !ccx.sess().no_landing_pads() {
596 attributes::emit_uwtable(lldecl, true);
599 let fn_ty = FnType::new(ccx, abi, &sig, &[]);
601 let fcx = FunctionContext::new(ccx, lldecl);
602 let mir = ccx.tcx().item_mir(instance.def);
603 mir::trans_mir(&fcx, fn_ty, &mir, instance, &sig, abi);
606 pub fn trans_ctor_shim<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
608 substs: &'tcx Substs<'tcx>,
610 llfndecl: ValueRef) {
611 attributes::inline(llfndecl, attributes::InlineAttr::Hint);
612 attributes::set_frame_pointer_elimination(ccx, llfndecl);
614 let ctor_ty = ccx.tcx().item_type(def_id);
615 let ctor_ty = monomorphize::apply_param_substs(ccx.shared(), substs, &ctor_ty);
617 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&ctor_ty.fn_sig());
618 let fn_ty = FnType::new(ccx, Abi::Rust, &sig, &[]);
620 let fcx = FunctionContext::new(ccx, llfndecl);
621 let bcx = fcx.get_entry_block();
622 if !fn_ty.ret.is_ignore() {
623 // But if there are no nested returns, we skip the indirection
624 // and have a single retslot
625 let dest = if fn_ty.ret.is_indirect() {
626 get_param(fcx.llfn, 0)
628 // We create an alloca to hold a pointer of type `ret.original_ty`
629 // which will hold the pointer to the right alloca which has the
631 fcx.alloca(fn_ty.ret.memory_ty(ccx), "sret_slot")
633 let dest_val = adt::MaybeSizedValue::sized(dest); // Can return unsized value
634 let mut llarg_idx = fn_ty.ret.is_indirect() as usize;
636 for (i, arg_ty) in sig.inputs().iter().enumerate() {
637 let lldestptr = adt::trans_field_ptr(&bcx, sig.output(), dest_val, Disr::from(disr), i);
638 let arg = &fn_ty.args[arg_idx];
640 if common::type_is_fat_ptr(bcx.ccx, arg_ty) {
641 let meta = &fn_ty.args[arg_idx];
643 arg.store_fn_arg(&bcx, &mut llarg_idx, get_dataptr(&bcx, lldestptr));
644 meta.store_fn_arg(&bcx, &mut llarg_idx, get_meta(&bcx, lldestptr));
646 arg.store_fn_arg(&bcx, &mut llarg_idx, lldestptr);
649 adt::trans_set_discr(&bcx, sig.output(), dest, disr);
651 if fn_ty.ret.is_indirect() {
656 if let Some(cast_ty) = fn_ty.ret.cast {
657 let load = bcx.load(bcx.pointercast(dest, cast_ty.ptr_to()));
658 let llalign = llalign_of_min(ccx, fn_ty.ret.ty);
660 llvm::LLVMSetAlignment(load, llalign);
664 bcx.ret(bcx.load(dest))
671 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
672 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
673 // applicable to variable declarations and may not really make sense for
674 // Rust code in the first place but whitelist them anyway and trust that
675 // the user knows what s/he's doing. Who knows, unanticipated use cases
676 // may pop up in the future.
678 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
679 // and don't have to be, LLVM treats them as no-ops.
681 "appending" => Some(llvm::Linkage::AppendingLinkage),
682 "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
683 "common" => Some(llvm::Linkage::CommonLinkage),
684 "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
685 "external" => Some(llvm::Linkage::ExternalLinkage),
686 "internal" => Some(llvm::Linkage::InternalLinkage),
687 "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
688 "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
689 "private" => Some(llvm::Linkage::PrivateLinkage),
690 "weak" => Some(llvm::Linkage::WeakAnyLinkage),
691 "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
696 pub fn set_link_section(ccx: &CrateContext,
698 attrs: &[ast::Attribute]) {
699 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
700 if contains_null(§.as_str()) {
701 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
704 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
705 llvm::LLVMSetSection(llval, buf.as_ptr());
710 /// Create the `main` function which will initialise the rust runtime and call
711 /// users’ main function.
712 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
713 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
714 Some((id, span)) => {
715 (ccx.tcx().map.local_def_id(id), span)
720 // check for the #[rustc_error] annotation, which forces an
721 // error in trans. This is used to write compile-fail tests
722 // that actually test that compilation succeeds without
723 // reporting an error.
724 if ccx.tcx().has_attr(main_def_id, "rustc_error") {
725 ccx.tcx().sess.span_fatal(span, "compilation successful");
728 let instance = Instance::mono(ccx.shared(), main_def_id);
730 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
731 // We want to create the wrapper in the same codegen unit as Rust's main
736 let main_llfn = Callee::def(ccx, main_def_id, instance.substs).reify(ccx);
738 let et = ccx.sess().entry_type.get().unwrap();
740 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
741 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
742 config::EntryNone => {} // Do nothing.
745 fn create_entry_fn(ccx: &CrateContext,
748 use_start_lang_item: bool) {
749 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
751 if declare::get_defined_value(ccx, "main").is_some() {
752 // FIXME: We should be smart and show a better diagnostic here.
753 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
754 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
756 ccx.sess().abort_if_errors();
759 let llfn = declare::declare_cfn(ccx, "main", llfty);
761 // `main` should respect same config for frame pointer elimination as rest of code
762 attributes::set_frame_pointer_elimination(ccx, llfn);
765 let name = CString::new("top").unwrap();
766 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, name.as_ptr())
768 let bld = Builder::with_ccx(ccx);
769 bld.position_at_end(llbb);
771 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
773 let (start_fn, args) = if use_start_lang_item {
774 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
775 let empty_substs = ccx.tcx().intern_substs(&[]);
776 let start_fn = Callee::def(ccx, start_def_id, empty_substs).reify(ccx);
777 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
780 debug!("using user-defined start fn");
781 (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
784 let result = bld.call(start_fn, &args, None);
789 fn contains_null(s: &str) -> bool {
790 s.bytes().any(|b| b == 0)
793 fn write_metadata(cx: &SharedCrateContext,
794 exported_symbols: &NodeSet) -> Vec<u8> {
797 #[derive(PartialEq, Eq, PartialOrd, Ord)]
804 let kind = cx.sess().crate_types.borrow().iter().map(|ty| {
806 config::CrateTypeExecutable |
807 config::CrateTypeStaticlib |
808 config::CrateTypeCdylib => MetadataKind::None,
810 config::CrateTypeRlib |
811 config::CrateTypeMetadata => MetadataKind::Uncompressed,
813 config::CrateTypeDylib |
814 config::CrateTypeProcMacro => MetadataKind::Compressed,
818 if kind == MetadataKind::None {
822 let cstore = &cx.tcx().sess.cstore;
823 let metadata = cstore.encode_metadata(cx.tcx(),
827 if kind == MetadataKind::Uncompressed {
831 assert!(kind == MetadataKind::Compressed);
832 let mut compressed = cstore.metadata_encoding_version().to_vec();
833 compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
835 let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
836 let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
837 let name = cx.metadata_symbol_name();
838 let buf = CString::new(name).unwrap();
839 let llglobal = unsafe {
840 llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
843 llvm::LLVMSetInitializer(llglobal, llconst);
845 cx.tcx().sess.cstore.metadata_section_name(&cx.sess().target.target);
846 let name = CString::new(section_name).unwrap();
847 llvm::LLVMSetSection(llglobal, name.as_ptr());
849 // Also generate a .section directive to force no
850 // flags, at least for ELF outputs, so that the
851 // metadata doesn't get loaded into memory.
852 let directive = format!(".section {}", section_name);
853 let directive = CString::new(directive).unwrap();
854 llvm::LLVMSetModuleInlineAsm(cx.metadata_llmod(), directive.as_ptr())
859 /// Find any symbols that are defined in one compilation unit, but not declared
860 /// in any other compilation unit. Give these symbols internal linkage.
861 fn internalize_symbols<'a, 'tcx>(sess: &Session,
862 ccxs: &CrateContextList<'a, 'tcx>,
863 symbol_map: &SymbolMap<'tcx>,
864 exported_symbols: &ExportedSymbols) {
865 let export_threshold =
866 symbol_export::crates_export_threshold(&sess.crate_types.borrow()[..]);
868 let exported_symbols = exported_symbols
869 .exported_symbols(LOCAL_CRATE)
871 .filter(|&&(_, export_level)| {
872 symbol_export::is_below_threshold(export_level, export_threshold)
874 .map(|&(ref name, _)| &name[..])
875 .collect::<FxHashSet<&str>>();
877 let scx = ccxs.shared();
880 let incr_comp = sess.opts.debugging_opts.incremental.is_some();
882 // 'unsafe' because we are holding on to CStr's from the LLVM module within
885 let mut referenced_somewhere = FxHashSet();
887 // Collect all symbols that need to stay externally visible because they
888 // are referenced via a declaration in some other codegen unit. In
889 // incremental compilation, we don't need to collect. See below for more
892 for ccx in ccxs.iter_need_trans() {
893 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
894 let linkage = llvm::LLVMRustGetLinkage(val);
895 // We only care about external declarations (not definitions)
896 // and available_externally definitions.
897 let is_available_externally =
898 linkage == llvm::Linkage::AvailableExternallyLinkage;
899 let is_decl = llvm::LLVMIsDeclaration(val) == llvm::True;
901 if is_decl || is_available_externally {
902 let symbol_name = CStr::from_ptr(llvm::LLVMGetValueName(val));
903 referenced_somewhere.insert(symbol_name);
909 // Also collect all symbols for which we cannot adjust linkage, because
910 // it is fixed by some directive in the source code.
911 let (locally_defined_symbols, linkage_fixed_explicitly) = {
912 let mut locally_defined_symbols = FxHashSet();
913 let mut linkage_fixed_explicitly = FxHashSet();
915 for trans_item in scx.translation_items().borrow().iter() {
916 let symbol_name = symbol_map.get_or_compute(scx, *trans_item);
917 if trans_item.explicit_linkage(tcx).is_some() {
918 linkage_fixed_explicitly.insert(symbol_name.clone());
920 locally_defined_symbols.insert(symbol_name);
923 (locally_defined_symbols, linkage_fixed_explicitly)
926 // Examine each external definition. If the definition is not used in
927 // any other compilation unit, and is not reachable from other crates,
928 // then give it internal linkage.
929 for ccx in ccxs.iter_need_trans() {
930 for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
931 let linkage = llvm::LLVMRustGetLinkage(val);
933 let is_externally_visible = (linkage == llvm::Linkage::ExternalLinkage) ||
934 (linkage == llvm::Linkage::LinkOnceODRLinkage) ||
935 (linkage == llvm::Linkage::WeakODRLinkage);
937 if !is_externally_visible {
938 // This symbol is not visible outside of its codegen unit,
939 // so there is nothing to do for it.
943 let name_cstr = CStr::from_ptr(llvm::LLVMGetValueName(val));
944 let name_str = name_cstr.to_str().unwrap();
946 if exported_symbols.contains(&name_str) {
947 // This symbol is explicitly exported, so we can't
948 // mark it as internal or hidden.
952 let is_declaration = llvm::LLVMIsDeclaration(val) == llvm::True;
955 if locally_defined_symbols.contains(name_str) {
956 // Only mark declarations from the current crate as hidden.
957 // Otherwise we would mark things as hidden that are
958 // imported from other crates or native libraries.
959 llvm::LLVMRustSetVisibility(val, llvm::Visibility::Hidden);
962 let has_fixed_linkage = linkage_fixed_explicitly.contains(name_str);
964 if !has_fixed_linkage {
965 // In incremental compilation mode, we can't be sure that
966 // we saw all references because we don't know what's in
967 // cached compilation units, so we always assume that the
968 // given item has been referenced.
969 if incr_comp || referenced_somewhere.contains(&name_cstr) {
970 llvm::LLVMRustSetVisibility(val, llvm::Visibility::Hidden);
972 llvm::LLVMRustSetLinkage(val, llvm::Linkage::InternalLinkage);
975 llvm::LLVMSetDLLStorageClass(val, llvm::DLLStorageClass::Default);
976 llvm::UnsetComdat(val);
984 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
985 // This is required to satisfy `dllimport` references to static data in .rlibs
986 // when using MSVC linker. We do this only for data, as linker can fix up
987 // code references on its own.
988 // See #26591, #27438
989 fn create_imps(cx: &CrateContextList) {
990 // The x86 ABI seems to require that leading underscores are added to symbol
991 // names, so we need an extra underscore on 32-bit. There's also a leading
992 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
993 // underscores added in front).
994 let prefix = if cx.shared().sess().target.target.target_pointer_width == "32" {
1000 for ccx in cx.iter_need_trans() {
1001 let exported: Vec<_> = iter_globals(ccx.llmod())
1003 llvm::LLVMRustGetLinkage(val) ==
1004 llvm::Linkage::ExternalLinkage &&
1005 llvm::LLVMIsDeclaration(val) == 0
1009 let i8p_ty = Type::i8p(&ccx);
1010 for val in exported {
1011 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
1012 let mut imp_name = prefix.as_bytes().to_vec();
1013 imp_name.extend(name.to_bytes());
1014 let imp_name = CString::new(imp_name).unwrap();
1015 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
1017 imp_name.as_ptr() as *const _);
1018 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
1019 llvm::LLVMSetInitializer(imp, init);
1020 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1028 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
1031 impl Iterator for ValueIter {
1032 type Item = ValueRef;
1034 fn next(&mut self) -> Option<ValueRef> {
1037 self.cur = unsafe { (self.step)(old) };
1045 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
1048 cur: llvm::LLVMGetFirstGlobal(llmod),
1049 step: llvm::LLVMGetNextGlobal,
1054 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
1057 cur: llvm::LLVMGetFirstFunction(llmod),
1058 step: llvm::LLVMGetNextFunction,
1063 /// The context provided lists a set of reachable ids as calculated by
1064 /// middle::reachable, but this contains far more ids and symbols than we're
1065 /// actually exposing from the object file. This function will filter the set in
1066 /// the context to the set of ids which correspond to symbols that are exposed
1067 /// from the object file being generated.
1069 /// This list is later used by linkers to determine the set of symbols needed to
1070 /// be exposed from a dynamic library and it's also encoded into the metadata.
1071 pub fn find_exported_symbols(tcx: TyCtxt, reachable: NodeSet) -> NodeSet {
1072 reachable.into_iter().filter(|&id| {
1073 // Next, we want to ignore some FFI functions that are not exposed from
1074 // this crate. Reachable FFI functions can be lumped into two
1077 // 1. Those that are included statically via a static library
1078 // 2. Those included otherwise (e.g. dynamically or via a framework)
1080 // Although our LLVM module is not literally emitting code for the
1081 // statically included symbols, it's an export of our library which
1082 // needs to be passed on to the linker and encoded in the metadata.
1084 // As a result, if this id is an FFI item (foreign item) then we only
1085 // let it through if it's included statically.
1086 match tcx.map.get(id) {
1087 hir_map::NodeForeignItem(..) => {
1088 let def_id = tcx.map.local_def_id(id);
1089 tcx.sess.cstore.is_statically_included_foreign_item(def_id)
1092 // Only consider nodes that actually have exported symbols.
1093 hir_map::NodeItem(&hir::Item {
1094 node: hir::ItemStatic(..), .. }) |
1095 hir_map::NodeItem(&hir::Item {
1096 node: hir::ItemFn(..), .. }) |
1097 hir_map::NodeImplItem(&hir::ImplItem {
1098 node: hir::ImplItemKind::Method(..), .. }) => {
1099 let def_id = tcx.map.local_def_id(id);
1100 let generics = tcx.item_generics(def_id);
1101 let attributes = tcx.get_attrs(def_id);
1102 (generics.parent_types == 0 && generics.types.is_empty()) &&
1103 // Functions marked with #[inline] are only ever translated
1104 // with "internal" linkage and are never exported.
1105 !attr::requests_inline(&attributes[..])
1113 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1114 analysis: ty::CrateAnalysis,
1115 incremental_hashes_map: &IncrementalHashesMap)
1116 -> CrateTranslation {
1117 let _task = tcx.dep_graph.in_task(DepNode::TransCrate);
1119 // Be careful with this krate: obviously it gives access to the
1120 // entire contents of the krate. So if you push any subtasks of
1121 // `TransCrate`, you need to be careful to register "reads" of the
1122 // particular items that will be processed.
1123 let krate = tcx.map.krate();
1125 let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
1126 let exported_symbols = find_exported_symbols(tcx, reachable);
1128 let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
1131 tcx.sess.opts.debug_assertions
1134 let link_meta = link::build_link_meta(incremental_hashes_map, &name);
1136 let shared_ccx = SharedCrateContext::new(tcx,
1141 // Translate the metadata.
1142 let metadata = time(tcx.sess.time_passes(), "write metadata", || {
1143 write_metadata(&shared_ccx, shared_ccx.exported_symbols())
1146 let metadata_module = ModuleTranslation {
1147 name: "metadata".to_string(),
1148 symbol_name_hash: 0, // we always rebuild metadata, at least for now
1149 source: ModuleSource::Translated(ModuleLlvm {
1150 llcx: shared_ccx.metadata_llcx(),
1151 llmod: shared_ccx.metadata_llmod(),
1154 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
1156 // Run the translation item collector and partition the collected items into
1158 let (codegen_units, symbol_map) = collect_and_partition_translation_items(&shared_ccx);
1160 let symbol_map = Rc::new(symbol_map);
1162 let previous_work_products = trans_reuse_previous_work_products(&shared_ccx,
1166 let crate_context_list = CrateContextList::new(&shared_ccx,
1168 previous_work_products,
1169 symbol_map.clone());
1170 let modules: Vec<_> = crate_context_list.iter_all()
1172 let source = match ccx.previous_work_product() {
1173 Some(buf) => ModuleSource::Preexisting(buf.clone()),
1174 None => ModuleSource::Translated(ModuleLlvm {
1181 name: String::from(ccx.codegen_unit().name()),
1182 symbol_name_hash: ccx.codegen_unit()
1183 .compute_symbol_name_hash(&shared_ccx,
1190 assert_module_sources::assert_module_sources(tcx, &modules);
1192 // Skip crate items and just output metadata in -Z no-trans mode.
1193 if tcx.sess.opts.debugging_opts.no_trans ||
1194 tcx.sess.crate_types.borrow().iter().all(|ct| ct == &config::CrateTypeMetadata) {
1195 let linker_info = LinkerInfo::new(&shared_ccx, &ExportedSymbols::empty());
1196 return CrateTranslation {
1198 metadata_module: metadata_module,
1201 exported_symbols: ExportedSymbols::empty(),
1202 no_builtins: no_builtins,
1203 linker_info: linker_info,
1204 windows_subsystem: None,
1208 // Instantiate translation items without filling out definitions yet...
1209 for ccx in crate_context_list.iter_need_trans() {
1210 let cgu = ccx.codegen_unit();
1211 let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
1213 tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
1214 for (trans_item, linkage) in trans_items {
1215 trans_item.predefine(&ccx, linkage);
1220 // ... and now that we have everything pre-defined, fill out those definitions.
1221 for ccx in crate_context_list.iter_need_trans() {
1222 let cgu = ccx.codegen_unit();
1223 let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
1224 tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
1225 for (trans_item, _) in trans_items {
1226 trans_item.define(&ccx);
1229 // If this codegen unit contains the main function, also create the
1231 maybe_create_entry_wrapper(&ccx);
1233 // Run replace-all-uses-with for statics that need it
1234 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1236 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1237 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1238 llvm::LLVMDeleteGlobal(old_g);
1242 // Finalize debuginfo
1243 if ccx.sess().opts.debuginfo != NoDebugInfo {
1244 debuginfo::finalize(&ccx);
1249 symbol_names_test::report_symbol_names(&shared_ccx);
1251 if shared_ccx.sess().trans_stats() {
1252 let stats = shared_ccx.stats();
1253 println!("--- trans stats ---");
1254 println!("n_glues_created: {}", stats.n_glues_created.get());
1255 println!("n_null_glues: {}", stats.n_null_glues.get());
1256 println!("n_real_glues: {}", stats.n_real_glues.get());
1258 println!("n_fns: {}", stats.n_fns.get());
1259 println!("n_inlines: {}", stats.n_inlines.get());
1260 println!("n_closures: {}", stats.n_closures.get());
1261 println!("fn stats:");
1262 stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1263 insns_b.cmp(&insns_a)
1265 for tuple in stats.fn_stats.borrow().iter() {
1267 (ref name, insns) => {
1268 println!("{} insns, {}", insns, *name);
1274 if shared_ccx.sess().count_llvm_insns() {
1275 for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
1276 println!("{:7} {}", *v, *k);
1280 let sess = shared_ccx.sess();
1282 let exported_symbols = ExportedSymbols::compute_from(&shared_ccx,
1285 // Now that we have all symbols that are exported from the CGUs of this
1286 // crate, we can run the `internalize_symbols` pass.
1287 time(shared_ccx.sess().time_passes(), "internalize symbols", || {
1288 internalize_symbols(sess,
1289 &crate_context_list,
1294 if tcx.sess.opts.debugging_opts.print_type_sizes {
1295 gather_type_sizes(tcx);
1298 if sess.target.target.options.is_like_msvc &&
1299 sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1300 create_imps(&crate_context_list);
1303 let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1305 let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1306 "windows_subsystem");
1307 let windows_subsystem = subsystem.map(|subsystem| {
1308 if subsystem != "windows" && subsystem != "console" {
1309 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1310 `windows` and `console` are allowed",
1313 subsystem.to_string()
1318 metadata_module: metadata_module,
1321 exported_symbols: exported_symbols,
1322 no_builtins: no_builtins,
1323 linker_info: linker_info,
1324 windows_subsystem: windows_subsystem,
1328 fn gather_type_sizes<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
1329 let layout_cache = tcx.layout_cache.borrow();
1330 for (ty, layout) in layout_cache.iter() {
1332 // (delay format until we actually need it)
1333 let record = |kind, opt_discr_size, variants| {
1334 let type_desc = format!("{:?}", ty);
1335 let overall_size = layout.size(&tcx.data_layout);
1336 let align = layout.align(&tcx.data_layout);
1337 tcx.sess.code_stats.borrow_mut().record_type_size(kind,
1345 let (adt_def, substs) = match ty.sty {
1346 ty::TyAdt(ref adt_def, substs) => {
1347 debug!("print-type-size t: `{:?}` process adt", ty);
1351 ty::TyClosure(..) => {
1352 debug!("print-type-size t: `{:?}` record closure", ty);
1353 record(DataTypeKind::Closure, None, vec![]);
1358 debug!("print-type-size t: `{:?}` skip non-nominal", ty);
1363 let adt_kind = adt_def.adt_kind();
1365 let build_field_info = |(field_name, field_ty): (ast::Name, Ty), offset: &layout::Size| {
1366 match layout_cache.get(&field_ty) {
1367 None => bug!("no layout found for field {} type: `{:?}`", field_name, field_ty),
1368 Some(field_layout) => {
1369 session::FieldInfo {
1370 name: field_name.to_string(),
1371 offset: offset.bytes(),
1372 size: field_layout.size(&tcx.data_layout).bytes(),
1373 align: field_layout.align(&tcx.data_layout).abi(),
1379 let build_primitive_info = |name: ast::Name, value: &layout::Primitive| {
1380 session::VariantInfo {
1381 name: Some(name.to_string()),
1382 kind: session::SizeKind::Exact,
1383 align: value.align(&tcx.data_layout).abi(),
1384 size: value.size(&tcx.data_layout).bytes(),
1390 WithDiscrim(&'a layout::Struct),
1391 NoDiscrim(&'a layout::Struct),
1394 let build_variant_info = |n: Option<ast::Name>, flds: &[(ast::Name, Ty)], layout: Fields| {
1395 let (s, field_offsets) = match layout {
1396 Fields::WithDiscrim(s) => (s, &s.offsets[1..]),
1397 Fields::NoDiscrim(s) => (s, &s.offsets[0..]),
1399 let field_info: Vec<_> = flds.iter()
1400 .zip(field_offsets.iter())
1401 .map(|(&field_name_ty, offset)| build_field_info(field_name_ty, offset))
1404 session::VariantInfo {
1405 name: n.map(|n|n.to_string()),
1407 session::SizeKind::Exact
1409 session::SizeKind::Min
1411 align: s.align.abi(),
1412 size: s.min_size.bytes(),
1418 Layout::StructWrappedNullablePointer { nonnull: ref variant_layout,
1421 discrfield_source: _ } => {
1422 debug!("print-type-size t: `{:?}` adt struct-wrapped nullable nndiscr {} is {:?}",
1423 ty, nndiscr, variant_layout);
1424 let variant_def = &adt_def.variants[nndiscr as usize];
1425 let fields: Vec<_> = variant_def.fields.iter()
1426 .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1428 record(adt_kind.into(),
1430 vec![build_variant_info(Some(variant_def.name),
1432 Fields::NoDiscrim(variant_layout))]);
1434 Layout::RawNullablePointer { nndiscr, value } => {
1435 debug!("print-type-size t: `{:?}` adt raw nullable nndiscr {} is {:?}",
1436 ty, nndiscr, value);
1437 let variant_def = &adt_def.variants[nndiscr as usize];
1438 record(adt_kind.into(), None,
1439 vec![build_primitive_info(variant_def.name, &value)]);
1441 Layout::Univariant { variant: ref variant_layout, non_zero: _ } => {
1442 let variant_names = || {
1443 adt_def.variants.iter().map(|v|format!("{}", v.name)).collect::<Vec<_>>()
1445 debug!("print-type-size t: `{:?}` adt univariant {:?} variants: {:?}",
1446 ty, variant_layout, variant_names());
1447 assert!(adt_def.variants.len() <= 1,
1448 "univariant with variants {:?}", variant_names());
1449 if adt_def.variants.len() == 1 {
1450 let variant_def = &adt_def.variants[0];
1451 let fields: Vec<_> = variant_def.fields.iter()
1452 .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1454 record(adt_kind.into(),
1456 vec![build_variant_info(Some(variant_def.name),
1458 Fields::NoDiscrim(variant_layout))]);
1460 // (This case arises for *empty* enums; so give it
1462 record(adt_kind.into(), None, vec![]);
1466 Layout::General { ref variants, discr, .. } => {
1467 debug!("print-type-size t: `{:?}` adt general variants def {} layouts {} {:?}",
1468 ty, adt_def.variants.len(), variants.len(), variants);
1469 let variant_infos: Vec<_> = adt_def.variants.iter()
1470 .zip(variants.iter())
1471 .map(|(variant_def, variant_layout)| {
1472 let fields: Vec<_> = variant_def.fields.iter()
1473 .map(|field_def| (field_def.name, field_def.ty(tcx, substs)))
1475 build_variant_info(Some(variant_def.name),
1477 Fields::WithDiscrim(variant_layout))
1480 record(adt_kind.into(), Some(discr.size()), variant_infos);
1483 Layout::UntaggedUnion { ref variants } => {
1484 debug!("print-type-size t: `{:?}` adt union variants {:?}",
1486 // layout does not currently store info about each
1488 record(adt_kind.into(), None, Vec::new());
1491 Layout::CEnum { discr, .. } => {
1492 debug!("print-type-size t: `{:?}` adt c-like enum", ty);
1493 let variant_infos: Vec<_> = adt_def.variants.iter()
1494 .map(|variant_def| {
1495 build_primitive_info(variant_def.name,
1496 &layout::Primitive::Int(discr))
1499 record(adt_kind.into(), Some(discr.size()), variant_infos);
1502 // other cases provide little interesting (i.e. adjustable
1503 // via representation tweaks) size info beyond total size.
1504 Layout::Scalar { .. } |
1505 Layout::Vector { .. } |
1506 Layout::Array { .. } |
1507 Layout::FatPointer { .. } => {
1508 debug!("print-type-size t: `{:?}` adt other", ty);
1509 record(adt_kind.into(), None, Vec::new())
1515 /// For each CGU, identify if we can reuse an existing object file (or
1516 /// maybe other context).
1517 fn trans_reuse_previous_work_products(scx: &SharedCrateContext,
1518 codegen_units: &[CodegenUnit],
1519 symbol_map: &SymbolMap)
1520 -> Vec<Option<WorkProduct>> {
1521 debug!("trans_reuse_previous_work_products()");
1525 let id = cgu.work_product_id();
1527 let hash = cgu.compute_symbol_name_hash(scx, symbol_map);
1529 debug!("trans_reuse_previous_work_products: id={:?} hash={}", id, hash);
1531 if let Some(work_product) = scx.dep_graph().previous_work_product(&id) {
1532 if work_product.input_hash == hash {
1533 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1534 return Some(work_product);
1536 if scx.sess().opts.debugging_opts.incremental_info {
1537 println!("incremental: CGU `{}` invalidated because of \
1538 changed partitioning hash.",
1541 debug!("trans_reuse_previous_work_products: \
1542 not reusing {:?} because hash changed to {:?}",
1543 work_product, hash);
1552 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>)
1553 -> (Vec<CodegenUnit<'tcx>>, SymbolMap<'tcx>) {
1554 let time_passes = scx.sess().time_passes();
1556 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1558 let mode_string = s.to_lowercase();
1559 let mode_string = mode_string.trim();
1560 if mode_string == "eager" {
1561 TransItemCollectionMode::Eager
1563 if mode_string != "lazy" {
1564 let message = format!("Unknown codegen-item collection mode '{}'. \
1565 Falling back to 'lazy' mode.",
1567 scx.sess().warn(&message);
1570 TransItemCollectionMode::Lazy
1573 None => TransItemCollectionMode::Lazy
1576 let (items, inlining_map) =
1577 time(time_passes, "translation item collection", || {
1578 collector::collect_crate_translation_items(&scx, collection_mode)
1581 let symbol_map = SymbolMap::build(scx, items.iter().cloned());
1583 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1584 PartitioningStrategy::PerModule
1586 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1589 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1590 partitioning::partition(scx,
1591 items.iter().cloned(),
1596 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1597 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1600 let mut ccx_map = scx.translation_items().borrow_mut();
1602 for trans_item in items.iter().cloned() {
1603 ccx_map.insert(trans_item);
1607 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1608 let mut item_to_cgus = FxHashMap();
1610 for cgu in &codegen_units {
1611 for (&trans_item, &linkage) in cgu.items() {
1612 item_to_cgus.entry(trans_item)
1613 .or_insert(Vec::new())
1614 .push((cgu.name().clone(), linkage));
1618 let mut item_keys: Vec<_> = items
1621 let mut output = i.to_string(scx.tcx());
1622 output.push_str(" @@");
1623 let mut empty = Vec::new();
1624 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1625 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1627 for &(ref cgu_name, linkage) in cgus.iter() {
1628 output.push_str(" ");
1629 output.push_str(&cgu_name[..]);
1631 let linkage_abbrev = match linkage {
1632 llvm::Linkage::ExternalLinkage => "External",
1633 llvm::Linkage::AvailableExternallyLinkage => "Available",
1634 llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1635 llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1636 llvm::Linkage::WeakAnyLinkage => "WeakAny",
1637 llvm::Linkage::WeakODRLinkage => "WeakODR",
1638 llvm::Linkage::AppendingLinkage => "Appending",
1639 llvm::Linkage::InternalLinkage => "Internal",
1640 llvm::Linkage::PrivateLinkage => "Private",
1641 llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1642 llvm::Linkage::CommonLinkage => "Common",
1645 output.push_str("[");
1646 output.push_str(linkage_abbrev);
1647 output.push_str("]");
1655 for item in item_keys {
1656 println!("TRANS_ITEM {}", item);
1660 (codegen_units, symbol_map)