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::ModuleLlvm;
27 use super::ModuleSource;
28 use super::ModuleTranslation;
29 use super::ModuleKind;
31 use assert_module_sources;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use back::write::{self, OngoingCrateTranslation};
36 use llvm::{ContextRef, Linkage, ModuleRef, ValueRef, Vector, get_param};
39 use rustc::hir::def_id::LOCAL_CRATE;
40 use rustc::middle::lang_items::StartFnLangItem;
41 use rustc::middle::cstore::{EncodedMetadata, EncodedMetadataHashes};
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::dep_graph::AssertDepGraphSafe;
44 use rustc::middle::cstore::LinkMeta;
45 use rustc::hir::map as hir_map;
46 use rustc::util::common::{time, print_time_passes_entry};
47 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType};
48 use rustc::session::Session;
49 use rustc_incremental::{self, IncrementalHashesMap};
52 use mir::lvalue::LvalueRef;
56 use common::{C_bool, C_bytes_in_context, C_i32, C_uint};
57 use collector::{self, TransItemCollectionMode};
58 use common::{C_struct_in_context, C_u64, C_undef, C_array};
59 use common::CrateContext;
60 use common::{type_is_zero_size, val_ty};
63 use context::{self, LocalCrateContext, SharedCrateContext, Stats};
69 use monomorphize::{self, Instance};
70 use partitioning::{self, PartitioningStrategy, CodegenUnit};
71 use symbol_names_test;
73 use trans_item::{TransItem, DefPathBasedNames};
77 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet};
80 use std::ffi::{CStr, CString};
83 use std::time::{Instant, Duration};
90 use mir::lvalue::Alignment;
92 pub struct StatRecorder<'a, 'tcx: 'a> {
93 ccx: &'a CrateContext<'a, 'tcx>,
98 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
99 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
100 let istart = ccx.stats().n_llvm_insns.get();
109 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
111 if self.ccx.sess().trans_stats() {
112 let iend = self.ccx.stats().n_llvm_insns.get();
113 self.ccx.stats().fn_stats.borrow_mut()
114 .push((self.name.take().unwrap(), iend - self.istart));
115 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
116 // Reset LLVM insn count to avoid compound costs.
117 self.ccx.stats().n_llvm_insns.set(self.istart);
122 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
123 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
126 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
127 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
130 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
132 -> llvm::IntPredicate {
134 hir::BiEq => llvm::IntEQ,
135 hir::BiNe => llvm::IntNE,
136 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
137 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
138 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
139 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
141 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
148 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
150 hir::BiEq => llvm::RealOEQ,
151 hir::BiNe => llvm::RealUNE,
152 hir::BiLt => llvm::RealOLT,
153 hir::BiLe => llvm::RealOLE,
154 hir::BiGt => llvm::RealOGT,
155 hir::BiGe => llvm::RealOGE,
157 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
164 pub fn compare_simd_types<'a, 'tcx>(
165 bcx: &Builder<'a, 'tcx>,
172 let signed = match t.sty {
174 let cmp = bin_op_to_fcmp_predicate(op);
175 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
177 ty::TyUint(_) => false,
178 ty::TyInt(_) => true,
179 _ => bug!("compare_simd_types: invalid SIMD type"),
182 let cmp = bin_op_to_icmp_predicate(op, signed);
183 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
184 // to get the correctly sized type. This will compile to a single instruction
185 // once the IR is converted to assembly if the SIMD instruction is supported
186 // by the target architecture.
187 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
190 /// Retrieve the information we are losing (making dynamic) in an unsizing
193 /// The `old_info` argument is a bit funny. It is intended for use
194 /// in an upcast, where the new vtable for an object will be drived
195 /// from the old one.
196 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
199 old_info: Option<ValueRef>)
201 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
202 match (&source.sty, &target.sty) {
203 (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
204 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
205 // For now, upcasts are limited to changes in marker
206 // traits, and hence never actually require an actual
207 // change to the vtable.
208 old_info.expect("unsized_info: missing old info for trait upcast")
210 (_, &ty::TyDynamic(ref data, ..)) => {
211 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
212 Type::vtable_ptr(ccx))
214 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
220 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
221 pub fn unsize_thin_ptr<'a, 'tcx>(
222 bcx: &Builder<'a, 'tcx>,
226 ) -> (ValueRef, ValueRef) {
227 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
228 match (&src_ty.sty, &dst_ty.sty) {
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 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
240 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
241 assert!(bcx.ccx.shared().type_is_sized(a));
242 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
243 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
245 _ => bug!("unsize_thin_ptr: called on bad types"),
249 /// Coerce `src`, which is a reference to a value of type `src_ty`,
250 /// to a value of type `dst_ty` and store the result in `dst`
251 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
252 src: &LvalueRef<'tcx>,
253 dst: &LvalueRef<'tcx>) {
254 let src_ty = src.ty.to_ty(bcx.tcx());
255 let dst_ty = dst.ty.to_ty(bcx.tcx());
256 let coerce_ptr = || {
257 let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
258 // fat-ptr to fat-ptr unsize preserves the vtable
259 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
260 // So we need to pointercast the base to ensure
261 // the types match up.
262 let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
263 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
264 let base = bcx.pointercast(base, llcast_ty);
267 let base = load_ty(bcx, src.llval, src.alignment, src_ty);
268 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
270 store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
272 match (&src_ty.sty, &dst_ty.sty) {
273 (&ty::TyRef(..), &ty::TyRef(..)) |
274 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
275 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
278 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
282 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
283 assert_eq!(def_a, def_b);
285 let src_fields = def_a.variants[0].fields.iter().map(|f| {
286 monomorphize::field_ty(bcx.tcx(), substs_a, f)
288 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
289 monomorphize::field_ty(bcx.tcx(), substs_b, f)
292 let iter = src_fields.zip(dst_fields).enumerate();
293 for (i, (src_fty, dst_fty)) in iter {
294 if type_is_zero_size(bcx.ccx, dst_fty) {
298 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
299 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
300 if src_fty == dst_fty {
301 memcpy_ty(bcx, dst_f, src_f, src_fty, None);
305 &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
306 &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
311 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
317 pub fn cast_shift_expr_rhs(
318 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
320 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
323 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
327 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
328 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
331 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
337 where F: FnOnce(ValueRef, Type) -> ValueRef,
338 G: FnOnce(ValueRef, Type) -> ValueRef
340 // Shifts may have any size int on the rhs
342 let mut rhs_llty = val_ty(rhs);
343 let mut lhs_llty = val_ty(lhs);
344 if rhs_llty.kind() == Vector {
345 rhs_llty = rhs_llty.element_type()
347 if lhs_llty.kind() == Vector {
348 lhs_llty = lhs_llty.element_type()
350 let rhs_sz = rhs_llty.int_width();
351 let lhs_sz = lhs_llty.int_width();
354 } else if lhs_sz > rhs_sz {
355 // FIXME (#1877: If shifting by negative
356 // values becomes not undefined then this is wrong.
366 /// Returns whether this session's target will use SEH-based unwinding.
368 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
369 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
370 /// 64-bit MinGW) instead of "full SEH".
371 pub fn wants_msvc_seh(sess: &Session) -> bool {
372 sess.target.target.options.is_like_msvc
375 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
376 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
377 b.call(assume_intrinsic, &[val], None);
380 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
381 /// differs from the type used for SSA values. Also handles various special cases where the type
382 /// gives us better information about what we are loading.
383 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
384 alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
386 if type_is_zero_size(ccx, t) {
387 return C_undef(type_of::type_of(ccx, t));
391 let global = llvm::LLVMIsAGlobalVariable(ptr);
392 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
393 let val = llvm::LLVMGetInitializer(global);
396 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
404 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
406 } else if t.is_char() {
407 // a char is a Unicode codepoint, and so takes values from 0
408 // to 0x10FFFF inclusive only.
409 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
410 } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
411 && !common::type_is_fat_ptr(ccx, t)
413 b.load_nonnull(ptr, alignment.to_align())
415 b.load(ptr, alignment.to_align())
419 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
420 /// differs from the type used for SSA values.
421 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
422 dst_align: Alignment, t: Ty<'tcx>) {
423 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
425 if common::type_is_fat_ptr(cx.ccx, t) {
426 let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
427 let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
428 store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
430 cx.store(from_immediate(cx, v), dst, dst_align.to_align());
434 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
438 dst_align: Alignment,
440 // FIXME: emit metadata
441 cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
442 cx.store(extra, get_meta(cx, dst), dst_align.to_align());
445 pub fn load_fat_ptr<'a, 'tcx>(
446 b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
447 ) -> (ValueRef, ValueRef) {
448 let ptr = get_dataptr(b, src);
449 let ptr = if t.is_region_ptr() || t.is_box() {
450 b.load_nonnull(ptr, alignment.to_align())
452 b.load(ptr, alignment.to_align())
455 let meta = get_meta(b, src);
456 let meta_ty = val_ty(meta);
457 // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
459 let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
460 b.load_nonnull(meta, None)
468 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
469 if val_ty(val) == Type::i1(bcx.ccx) {
470 bcx.zext(val, Type::i8(bcx.ccx))
476 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
478 bcx.trunc(val, Type::i1(bcx.ccx))
484 pub enum Lifetime { Start, End }
487 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
488 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
489 // and the intrinsic for `lt` and passes them to `emit`, which is in
490 // charge of generating code to call the passed intrinsic on whatever
491 // block of generated code is targetted for the intrinsic.
493 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
494 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
495 pub fn call(self, b: &Builder, ptr: ValueRef) {
496 if b.ccx.sess().opts.optimize == config::OptLevel::No {
500 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
505 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
506 Lifetime::Start => "llvm.lifetime.start",
507 Lifetime::End => "llvm.lifetime.end"
510 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
511 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
515 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
521 let ptr_width = &ccx.sess().target.target.target_pointer_width;
522 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
523 let memcpy = ccx.get_intrinsic(&key);
524 let src_ptr = b.pointercast(src, Type::i8p(ccx));
525 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
526 let size = b.intcast(n_bytes, ccx.int_type(), false);
527 let align = C_i32(ccx, align as i32);
528 let volatile = C_bool(ccx, false);
529 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
532 pub fn memcpy_ty<'a, 'tcx>(
533 bcx: &Builder<'a, 'tcx>,
541 let size = ccx.size_of(t);
546 let align = align.unwrap_or_else(|| ccx.align_of(t));
547 call_memcpy(bcx, dst, src, C_uint(ccx, size), align);
550 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
555 volatile: bool) -> ValueRef {
556 let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
557 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
558 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
559 let volatile = C_bool(b.ccx, volatile);
560 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
563 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
564 let _s = if ccx.sess().trans_stats() {
565 let mut instance_name = String::new();
566 DefPathBasedNames::new(ccx.tcx(), true, true)
567 .push_def_path(instance.def_id(), &mut instance_name);
568 Some(StatRecorder::new(ccx, instance_name))
573 // this is an info! to allow collecting monomorphization statistics
574 // and to allow finding the last function before LLVM aborts from
576 info!("trans_instance({})", instance);
578 let fn_ty = common::instance_ty(ccx.shared(), &instance);
579 let sig = common::ty_fn_sig(ccx, fn_ty);
580 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
582 let lldecl = match ccx.instances().borrow().get(&instance) {
584 None => bug!("Instance `{:?}` not already declared", instance)
587 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
589 // The `uwtable` attribute according to LLVM is:
591 // This attribute indicates that the ABI being targeted requires that an
592 // unwind table entry be produced for this function even if we can show
593 // that no exceptions passes by it. This is normally the case for the
594 // ELF x86-64 abi, but it can be disabled for some compilation units.
596 // Typically when we're compiling with `-C panic=abort` (which implies this
597 // `no_landing_pads` check) we don't need `uwtable` because we can't
598 // generate any exceptions! On Windows, however, exceptions include other
599 // events such as illegal instructions, segfaults, etc. This means that on
600 // Windows we end up still needing the `uwtable` attribute even if the `-C
601 // panic=abort` flag is passed.
603 // You can also find more info on why Windows is whitelisted here in:
604 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
605 if !ccx.sess().no_landing_pads() ||
606 ccx.sess().target.target.options.is_like_windows {
607 attributes::emit_uwtable(lldecl, true);
610 let mir = ccx.tcx().instance_mir(instance.def);
611 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
614 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
615 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
616 // applicable to variable declarations and may not really make sense for
617 // Rust code in the first place but whitelist them anyway and trust that
618 // the user knows what s/he's doing. Who knows, unanticipated use cases
619 // may pop up in the future.
621 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
622 // and don't have to be, LLVM treats them as no-ops.
624 "appending" => Some(llvm::Linkage::AppendingLinkage),
625 "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
626 "common" => Some(llvm::Linkage::CommonLinkage),
627 "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
628 "external" => Some(llvm::Linkage::ExternalLinkage),
629 "internal" => Some(llvm::Linkage::InternalLinkage),
630 "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
631 "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
632 "private" => Some(llvm::Linkage::PrivateLinkage),
633 "weak" => Some(llvm::Linkage::WeakAnyLinkage),
634 "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
639 pub fn set_link_section(ccx: &CrateContext,
641 attrs: &[ast::Attribute]) {
642 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
643 if contains_null(§.as_str()) {
644 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
647 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
648 llvm::LLVMSetSection(llval, buf.as_ptr());
653 // check for the #[rustc_error] annotation, which forces an
654 // error in trans. This is used to write compile-fail tests
655 // that actually test that compilation succeeds without
656 // reporting an error.
657 fn check_for_rustc_errors_attr(tcx: TyCtxt) {
658 if let Some((id, span)) = *tcx.sess.entry_fn.borrow() {
659 let main_def_id = tcx.hir.local_def_id(id);
661 if tcx.has_attr(main_def_id, "rustc_error") {
662 tcx.sess.span_fatal(span, "compilation successful");
667 /// Create the `main` function which will initialise the rust runtime and call
668 /// users main function.
669 fn maybe_create_entry_wrapper(ccx: &CrateContext) {
670 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
671 Some((id, span)) => {
672 (ccx.tcx().hir.local_def_id(id), span)
677 let instance = Instance::mono(ccx.tcx(), main_def_id);
679 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
680 // We want to create the wrapper in the same codegen unit as Rust's main
685 let main_llfn = callee::get_fn(ccx, instance);
687 let et = ccx.sess().entry_type.get().unwrap();
689 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
690 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
691 config::EntryNone => {} // Do nothing.
694 fn create_entry_fn(ccx: &CrateContext,
697 use_start_lang_item: bool) {
698 let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
700 if declare::get_defined_value(ccx, "main").is_some() {
701 // FIXME: We should be smart and show a better diagnostic here.
702 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
703 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
705 ccx.sess().abort_if_errors();
708 let llfn = declare::declare_cfn(ccx, "main", llfty);
710 // `main` should respect same config for frame pointer elimination as rest of code
711 attributes::set_frame_pointer_elimination(ccx, llfn);
713 let bld = Builder::new_block(ccx, llfn, "top");
715 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
717 let (start_fn, args) = if use_start_lang_item {
718 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
719 let start_instance = Instance::mono(ccx.tcx(), start_def_id);
720 let start_fn = callee::get_fn(ccx, start_instance);
721 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
724 debug!("using user-defined start fn");
725 (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
728 let result = bld.call(start_fn, &args, None);
733 fn contains_null(s: &str) -> bool {
734 s.bytes().any(|b| b == 0)
737 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
738 link_meta: &LinkMeta,
739 exported_symbols: &NodeSet)
740 -> (ContextRef, ModuleRef,
741 EncodedMetadata, EncodedMetadataHashes) {
743 use flate2::Compression;
744 use flate2::write::DeflateEncoder;
746 let (metadata_llcx, metadata_llmod) = unsafe {
747 context::create_context_and_module(tcx.sess, "metadata")
750 #[derive(PartialEq, Eq, PartialOrd, Ord)]
757 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
759 config::CrateTypeExecutable |
760 config::CrateTypeStaticlib |
761 config::CrateTypeCdylib => MetadataKind::None,
763 config::CrateTypeRlib => MetadataKind::Uncompressed,
765 config::CrateTypeDylib |
766 config::CrateTypeProcMacro => MetadataKind::Compressed,
770 if kind == MetadataKind::None {
771 return (metadata_llcx,
773 EncodedMetadata::new(),
774 EncodedMetadataHashes::new());
777 let cstore = &tcx.sess.cstore;
778 let (metadata, hashes) = cstore.encode_metadata(tcx,
781 if kind == MetadataKind::Uncompressed {
782 return (metadata_llcx, metadata_llmod, metadata, hashes);
785 assert!(kind == MetadataKind::Compressed);
786 let mut compressed = cstore.metadata_encoding_version().to_vec();
787 DeflateEncoder::new(&mut compressed, Compression::Fast)
788 .write_all(&metadata.raw_data).unwrap();
790 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
791 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
792 let name = symbol_export::metadata_symbol_name(tcx);
793 let buf = CString::new(name).unwrap();
794 let llglobal = unsafe {
795 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
798 llvm::LLVMSetInitializer(llglobal, llconst);
799 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
800 let name = CString::new(section_name).unwrap();
801 llvm::LLVMSetSection(llglobal, name.as_ptr());
803 // Also generate a .section directive to force no
804 // flags, at least for ELF outputs, so that the
805 // metadata doesn't get loaded into memory.
806 let directive = format!(".section {}", section_name);
807 let directive = CString::new(directive).unwrap();
808 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
810 return (metadata_llcx, metadata_llmod, metadata, hashes);
813 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
814 // This is required to satisfy `dllimport` references to static data in .rlibs
815 // when using MSVC linker. We do this only for data, as linker can fix up
816 // code references on its own.
817 // See #26591, #27438
818 fn create_imps(sess: &Session,
819 llvm_module: &ModuleLlvm) {
820 // The x86 ABI seems to require that leading underscores are added to symbol
821 // names, so we need an extra underscore on 32-bit. There's also a leading
822 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
823 // underscores added in front).
824 let prefix = if sess.target.target.target_pointer_width == "32" {
830 let exported: Vec<_> = iter_globals(llvm_module.llmod)
832 llvm::LLVMRustGetLinkage(val) ==
833 llvm::Linkage::ExternalLinkage &&
834 llvm::LLVMIsDeclaration(val) == 0
838 let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
839 for val in exported {
840 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
841 let mut imp_name = prefix.as_bytes().to_vec();
842 imp_name.extend(name.to_bytes());
843 let imp_name = CString::new(imp_name).unwrap();
844 let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
846 imp_name.as_ptr() as *const _);
847 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
848 llvm::LLVMSetInitializer(imp, init);
849 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
856 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
859 impl Iterator for ValueIter {
860 type Item = ValueRef;
862 fn next(&mut self) -> Option<ValueRef> {
865 self.cur = unsafe { (self.step)(old) };
873 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
876 cur: llvm::LLVMGetFirstGlobal(llmod),
877 step: llvm::LLVMGetNextGlobal,
882 /// The context provided lists a set of reachable ids as calculated by
883 /// middle::reachable, but this contains far more ids and symbols than we're
884 /// actually exposing from the object file. This function will filter the set in
885 /// the context to the set of ids which correspond to symbols that are exposed
886 /// from the object file being generated.
888 /// This list is later used by linkers to determine the set of symbols needed to
889 /// be exposed from a dynamic library and it's also encoded into the metadata.
890 pub fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet {
891 reachable.iter().cloned().filter(|&id| {
892 // Next, we want to ignore some FFI functions that are not exposed from
893 // this crate. Reachable FFI functions can be lumped into two
896 // 1. Those that are included statically via a static library
897 // 2. Those included otherwise (e.g. dynamically or via a framework)
899 // Although our LLVM module is not literally emitting code for the
900 // statically included symbols, it's an export of our library which
901 // needs to be passed on to the linker and encoded in the metadata.
903 // As a result, if this id is an FFI item (foreign item) then we only
904 // let it through if it's included statically.
905 match tcx.hir.get(id) {
906 hir_map::NodeForeignItem(..) => {
907 let def_id = tcx.hir.local_def_id(id);
908 tcx.sess.cstore.is_statically_included_foreign_item(def_id)
911 // Only consider nodes that actually have exported symbols.
912 hir_map::NodeItem(&hir::Item {
913 node: hir::ItemStatic(..), .. }) |
914 hir_map::NodeItem(&hir::Item {
915 node: hir::ItemFn(..), .. }) |
916 hir_map::NodeImplItem(&hir::ImplItem {
917 node: hir::ImplItemKind::Method(..), .. }) => {
918 let def_id = tcx.hir.local_def_id(id);
919 let generics = tcx.generics_of(def_id);
920 let attributes = tcx.get_attrs(def_id);
921 (generics.parent_types == 0 && generics.types.is_empty()) &&
922 // Functions marked with #[inline] are only ever translated
923 // with "internal" linkage and are never exported.
924 !attr::requests_inline(&attributes)
932 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
933 analysis: ty::CrateAnalysis,
934 incremental_hashes_map: IncrementalHashesMap,
935 output_filenames: &OutputFilenames)
936 -> OngoingCrateTranslation {
937 check_for_rustc_errors_attr(tcx);
939 // Be careful with this krate: obviously it gives access to the
940 // entire contents of the krate. So if you push any subtasks of
941 // `TransCrate`, you need to be careful to register "reads" of the
942 // particular items that will be processed.
943 let krate = tcx.hir.krate();
944 let ty::CrateAnalysis { reachable, .. } = analysis;
945 let check_overflow = tcx.sess.overflow_checks();
946 let link_meta = link::build_link_meta(&incremental_hashes_map);
947 let exported_symbol_node_ids = find_exported_symbols(tcx, &reachable);
949 let shared_ccx = SharedCrateContext::new(tcx,
952 // Translate the metadata.
953 let (metadata_llcx, metadata_llmod, metadata, metadata_incr_hashes) =
954 time(tcx.sess.time_passes(), "write metadata", || {
955 write_metadata(tcx, &link_meta, &exported_symbol_node_ids)
958 let metadata_module = ModuleTranslation {
959 name: link::METADATA_MODULE_NAME.to_string(),
960 symbol_name_hash: 0, // we always rebuild metadata, at least for now
961 source: ModuleSource::Translated(ModuleLlvm {
963 llmod: metadata_llmod,
965 kind: ModuleKind::Metadata,
968 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
969 let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
970 Some(time_graph::TimeGraph::new())
975 // Skip crate items and just output metadata in -Z no-trans mode.
976 if tcx.sess.opts.debugging_opts.no_trans ||
977 !tcx.sess.opts.output_types.should_trans() {
978 let empty_exported_symbols = ExportedSymbols::empty();
979 let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
980 let ongoing_translation = write::start_async_translation(
984 tcx.crate_name(LOCAL_CRATE),
987 Arc::new(empty_exported_symbols),
993 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, metadata_module, true);
995 assert_and_save_dep_graph(tcx,
996 incremental_hashes_map,
997 metadata_incr_hashes,
1000 ongoing_translation.check_for_errors(tcx.sess);
1002 return ongoing_translation;
1005 let exported_symbols = Arc::new(ExportedSymbols::compute(tcx,
1006 &exported_symbol_node_ids));
1008 // Run the translation item collector and partition the collected items into
1010 let (translation_items, codegen_units) =
1011 collect_and_partition_translation_items(&shared_ccx, &exported_symbols);
1013 assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
1015 let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1016 let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1017 "windows_subsystem");
1018 let windows_subsystem = subsystem.map(|subsystem| {
1019 if subsystem != "windows" && subsystem != "console" {
1020 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1021 `windows` and `console` are allowed",
1024 subsystem.to_string()
1027 let no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1028 (tcx.sess.target.target.options.no_integrated_as &&
1029 (output_filenames.outputs.contains_key(&OutputType::Object) ||
1030 output_filenames.outputs.contains_key(&OutputType::Exe)));
1032 let ongoing_translation = write::start_async_translation(
1036 tcx.crate_name(LOCAL_CRATE),
1039 exported_symbols.clone(),
1045 // Translate an allocator shim, if any
1047 // If LTO is enabled and we've got some previous LLVM module we translated
1048 // above, then we can just translate directly into that LLVM module. If not,
1049 // however, we need to create a separate module and trans into that. Note
1050 // that the separate translation is critical for the standard library where
1051 // the rlib's object file doesn't have allocator functions but the dylib
1052 // links in an object file that has allocator functions. When we're
1053 // compiling a final LTO artifact, though, there's no need to worry about
1054 // this as we're not working with this dual "rlib/dylib" functionality.
1055 let allocator_module = if tcx.sess.lto() {
1057 } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1060 context::create_context_and_module(tcx.sess, "allocator");
1061 let modules = ModuleLlvm {
1065 time(tcx.sess.time_passes(), "write allocator module", || {
1066 allocator::trans(tcx, &modules, kind)
1069 Some(ModuleTranslation {
1070 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1071 symbol_name_hash: 0, // we always rebuild allocator shims
1072 source: ModuleSource::Translated(modules),
1073 kind: ModuleKind::Allocator,
1080 if let Some(allocator_module) = allocator_module {
1081 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, allocator_module, false);
1084 let codegen_unit_count = codegen_units.len();
1085 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess,
1087 codegen_unit_count == 0);
1089 let translation_items = Arc::new(translation_items);
1091 let mut all_stats = Stats::default();
1092 let mut module_dispositions = tcx.sess.opts.incremental.as_ref().map(|_| Vec::new());
1094 // We sort the codegen units by size. This way we can schedule work for LLVM
1095 // a bit more efficiently. Note that "size" is defined rather crudely at the
1096 // moment as it is just the number of TransItems in the CGU, not taking into
1097 // account the size of each TransItem.
1098 let codegen_units = {
1099 let mut codegen_units = codegen_units;
1100 codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
1104 let mut total_trans_time = Duration::new(0, 0);
1106 for (cgu_index, cgu) in codegen_units.into_iter().enumerate() {
1107 ongoing_translation.wait_for_signal_to_translate_item();
1108 ongoing_translation.check_for_errors(tcx.sess);
1110 let start_time = Instant::now();
1113 let _timing_guard = time_graph
1115 .map(|time_graph| time_graph.start(write::TRANS_WORKER_TIMELINE,
1116 write::TRANS_WORK_PACKAGE_KIND));
1117 let dep_node = cgu.work_product_dep_node();
1118 let ((stats, module), _) =
1119 tcx.dep_graph.with_task(dep_node,
1120 AssertDepGraphSafe(&shared_ccx),
1121 AssertDepGraphSafe((cgu,
1122 translation_items.clone(),
1123 exported_symbols.clone())),
1124 module_translation);
1125 all_stats.extend(stats);
1127 if let Some(ref mut module_dispositions) = module_dispositions {
1128 module_dispositions.push(module.disposition());
1134 let time_to_translate = Instant::now().duration_since(start_time);
1136 // We assume that the cost to run LLVM on a CGU is proportional to
1137 // the time we needed for translating it.
1138 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1139 time_to_translate.subsec_nanos() as u64;
1141 total_trans_time += time_to_translate;
1143 let is_last_cgu = (cgu_index + 1) == codegen_unit_count;
1145 ongoing_translation.submit_translated_module_to_llvm(tcx.sess,
1149 ongoing_translation.check_for_errors(tcx.sess);
1152 // Since the main thread is sometimes blocked during trans, we keep track
1153 // -Ztime-passes output manually.
1154 print_time_passes_entry(tcx.sess.time_passes(),
1155 "translate to LLVM IR",
1158 if let Some(module_dispositions) = module_dispositions {
1159 assert_module_sources::assert_module_sources(tcx, &module_dispositions);
1162 fn module_translation<'a, 'tcx>(
1163 scx: AssertDepGraphSafe<&SharedCrateContext<'a, 'tcx>>,
1164 args: AssertDepGraphSafe<(CodegenUnit<'tcx>,
1165 Arc<FxHashSet<TransItem<'tcx>>>,
1166 Arc<ExportedSymbols>)>)
1167 -> (Stats, ModuleTranslation)
1169 // FIXME(#40304): We ought to be using the id as a key and some queries, I think.
1170 let AssertDepGraphSafe(scx) = scx;
1171 let AssertDepGraphSafe((cgu, crate_trans_items, exported_symbols)) = args;
1173 let cgu_name = String::from(cgu.name());
1174 let cgu_id = cgu.work_product_id();
1175 let symbol_name_hash = cgu.compute_symbol_name_hash(scx, &exported_symbols);
1177 // Check whether there is a previous work-product we can
1178 // re-use. Not only must the file exist, and the inputs not
1179 // be dirty, but the hash of the symbols we will generate must
1181 let previous_work_product =
1182 scx.dep_graph().previous_work_product(&cgu_id).and_then(|work_product| {
1183 if work_product.input_hash == symbol_name_hash {
1184 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1187 if scx.sess().opts.debugging_opts.incremental_info {
1188 eprintln!("incremental: CGU `{}` invalidated because of \
1189 changed partitioning hash.",
1192 debug!("trans_reuse_previous_work_products: \
1193 not reusing {:?} because hash changed to {:?}",
1194 work_product, symbol_name_hash);
1199 if let Some(buf) = previous_work_product {
1200 // Don't need to translate this module.
1201 let module = ModuleTranslation {
1204 source: ModuleSource::Preexisting(buf.clone()),
1205 kind: ModuleKind::Regular,
1207 return (Stats::default(), module);
1210 // Instantiate translation items without filling out definitions yet...
1211 let lcx = LocalCrateContext::new(scx, cgu, crate_trans_items, exported_symbols);
1213 let ccx = CrateContext::new(scx, &lcx);
1214 let trans_items = ccx.codegen_unit()
1215 .items_in_deterministic_order(ccx.tcx());
1216 for &(trans_item, (linkage, visibility)) in &trans_items {
1217 trans_item.predefine(&ccx, linkage, visibility);
1220 // ... and now that we have everything pre-defined, fill out those definitions.
1221 for &(trans_item, _) in &trans_items {
1222 trans_item.define(&ccx);
1225 // If this codegen unit contains the main function, also create the
1227 maybe_create_entry_wrapper(&ccx);
1229 // Run replace-all-uses-with for statics that need it
1230 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1232 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1233 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1234 llvm::LLVMDeleteGlobal(old_g);
1238 // Create the llvm.used variable
1239 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1240 if !ccx.used_statics().borrow().is_empty() {
1241 let name = CString::new("llvm.used").unwrap();
1242 let section = CString::new("llvm.metadata").unwrap();
1243 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1246 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1247 val_ty(array).to_ref(),
1249 llvm::LLVMSetInitializer(g, array);
1250 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1251 llvm::LLVMSetSection(g, section.as_ptr());
1255 // Finalize debuginfo
1256 if ccx.sess().opts.debuginfo != NoDebugInfo {
1257 debuginfo::finalize(&ccx);
1260 let llvm_module = ModuleLlvm {
1265 // In LTO mode we inject the allocator shim into the existing
1267 if ccx.sess().lto() {
1268 if let Some(kind) = ccx.sess().allocator_kind.get() {
1269 time(ccx.sess().time_passes(), "write allocator module", || {
1271 allocator::trans(ccx.tcx(), &llvm_module, kind);
1277 // Adjust exported symbols for MSVC dllimport
1278 if ccx.sess().target.target.options.is_like_msvc &&
1279 ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1280 create_imps(ccx.sess(), &llvm_module);
1286 source: ModuleSource::Translated(llvm_module),
1287 kind: ModuleKind::Regular,
1291 (lcx.into_stats(), module)
1294 symbol_names_test::report_symbol_names(tcx);
1296 if shared_ccx.sess().trans_stats() {
1297 println!("--- trans stats ---");
1298 println!("n_glues_created: {}", all_stats.n_glues_created.get());
1299 println!("n_null_glues: {}", all_stats.n_null_glues.get());
1300 println!("n_real_glues: {}", all_stats.n_real_glues.get());
1302 println!("n_fns: {}", all_stats.n_fns.get());
1303 println!("n_inlines: {}", all_stats.n_inlines.get());
1304 println!("n_closures: {}", all_stats.n_closures.get());
1305 println!("fn stats:");
1306 all_stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1307 insns_b.cmp(&insns_a)
1309 for tuple in all_stats.fn_stats.borrow().iter() {
1311 (ref name, insns) => {
1312 println!("{} insns, {}", insns, *name);
1318 if shared_ccx.sess().count_llvm_insns() {
1319 for (k, v) in all_stats.llvm_insns.borrow().iter() {
1320 println!("{:7} {}", *v, *k);
1324 ongoing_translation.check_for_errors(tcx.sess);
1326 assert_and_save_dep_graph(tcx,
1327 incremental_hashes_map,
1328 metadata_incr_hashes,
1333 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1334 incremental_hashes_map: IncrementalHashesMap,
1335 metadata_incr_hashes: EncodedMetadataHashes,
1336 link_meta: LinkMeta) {
1337 time(tcx.sess.time_passes(),
1339 || rustc_incremental::assert_dep_graph(tcx));
1341 time(tcx.sess.time_passes(),
1342 "serialize dep graph",
1343 || rustc_incremental::save_dep_graph(tcx,
1344 incremental_hashes_map,
1345 &metadata_incr_hashes,
1346 link_meta.crate_hash));
1349 #[inline(never)] // give this a place in the profiler
1350 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1351 where I: Iterator<Item=&'a TransItem<'tcx>>
1353 let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1354 (trans_item, trans_item.symbol_name(tcx))
1357 (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1361 for pair in (&symbols[..]).windows(2) {
1362 let sym1 = &pair[0].1;
1363 let sym2 = &pair[1].1;
1366 let trans_item1 = pair[0].0;
1367 let trans_item2 = pair[1].0;
1369 let span1 = trans_item1.local_span(tcx);
1370 let span2 = trans_item2.local_span(tcx);
1372 // Deterministically select one of the spans for error reporting
1373 let span = match (span1, span2) {
1374 (Some(span1), Some(span2)) => {
1375 Some(if span1.lo.0 > span2.lo.0 {
1381 (Some(span), None) |
1382 (None, Some(span)) => Some(span),
1386 let error_message = format!("symbol `{}` is already defined", sym1);
1388 if let Some(span) = span {
1389 tcx.sess.span_fatal(span, &error_message)
1391 tcx.sess.fatal(&error_message)
1397 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
1398 exported_symbols: &ExportedSymbols)
1399 -> (FxHashSet<TransItem<'tcx>>,
1400 Vec<CodegenUnit<'tcx>>) {
1401 let time_passes = scx.sess().time_passes();
1403 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1405 let mode_string = s.to_lowercase();
1406 let mode_string = mode_string.trim();
1407 if mode_string == "eager" {
1408 TransItemCollectionMode::Eager
1410 if mode_string != "lazy" {
1411 let message = format!("Unknown codegen-item collection mode '{}'. \
1412 Falling back to 'lazy' mode.",
1414 scx.sess().warn(&message);
1417 TransItemCollectionMode::Lazy
1420 None => TransItemCollectionMode::Lazy
1423 let (items, inlining_map) =
1424 time(time_passes, "translation item collection", || {
1425 collector::collect_crate_translation_items(&scx,
1430 assert_symbols_are_distinct(scx.tcx(), items.iter());
1432 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1433 PartitioningStrategy::PerModule
1435 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1438 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1439 partitioning::partition(scx,
1440 items.iter().cloned(),
1446 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1447 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1449 let translation_items: FxHashSet<TransItem<'tcx>> = items.iter().cloned().collect();
1451 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1452 let mut item_to_cgus = FxHashMap();
1454 for cgu in &codegen_units {
1455 for (&trans_item, &linkage) in cgu.items() {
1456 item_to_cgus.entry(trans_item)
1457 .or_insert(Vec::new())
1458 .push((cgu.name().clone(), linkage));
1462 let mut item_keys: Vec<_> = items
1465 let mut output = i.to_string(scx.tcx());
1466 output.push_str(" @@");
1467 let mut empty = Vec::new();
1468 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1469 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1471 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1472 output.push_str(" ");
1473 output.push_str(&cgu_name);
1475 let linkage_abbrev = match linkage {
1476 llvm::Linkage::ExternalLinkage => "External",
1477 llvm::Linkage::AvailableExternallyLinkage => "Available",
1478 llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1479 llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1480 llvm::Linkage::WeakAnyLinkage => "WeakAny",
1481 llvm::Linkage::WeakODRLinkage => "WeakODR",
1482 llvm::Linkage::AppendingLinkage => "Appending",
1483 llvm::Linkage::InternalLinkage => "Internal",
1484 llvm::Linkage::PrivateLinkage => "Private",
1485 llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1486 llvm::Linkage::CommonLinkage => "Common",
1489 output.push_str("[");
1490 output.push_str(linkage_abbrev);
1491 output.push_str("]");
1499 for item in item_keys {
1500 println!("TRANS_ITEM {}", item);
1504 (translation_items, codegen_units)