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::{self, LinkMeta, LinkagePreference};
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_usize};
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};
81 use std::ffi::{CStr, CString};
84 use std::time::{Instant, Duration};
91 use mir::lvalue::Alignment;
93 pub struct StatRecorder<'a, 'tcx: 'a> {
94 ccx: &'a CrateContext<'a, 'tcx>,
99 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
100 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
101 let istart = ccx.stats().n_llvm_insns.get();
110 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
112 if self.ccx.sess().trans_stats() {
113 let iend = self.ccx.stats().n_llvm_insns.get();
114 self.ccx.stats().fn_stats.borrow_mut()
115 .push((self.name.take().unwrap(), iend - self.istart));
116 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
117 // Reset LLVM insn count to avoid compound costs.
118 self.ccx.stats().n_llvm_insns.set(self.istart);
123 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
124 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
127 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
128 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
131 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
133 -> llvm::IntPredicate {
135 hir::BiEq => llvm::IntEQ,
136 hir::BiNe => llvm::IntNE,
137 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
138 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
139 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
140 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
142 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
149 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
151 hir::BiEq => llvm::RealOEQ,
152 hir::BiNe => llvm::RealUNE,
153 hir::BiLt => llvm::RealOLT,
154 hir::BiLe => llvm::RealOLE,
155 hir::BiGt => llvm::RealOGT,
156 hir::BiGe => llvm::RealOGE,
158 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
165 pub fn compare_simd_types<'a, 'tcx>(
166 bcx: &Builder<'a, 'tcx>,
173 let signed = match t.sty {
175 let cmp = bin_op_to_fcmp_predicate(op);
176 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
178 ty::TyUint(_) => false,
179 ty::TyInt(_) => true,
180 _ => bug!("compare_simd_types: invalid SIMD type"),
183 let cmp = bin_op_to_icmp_predicate(op, signed);
184 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
185 // to get the correctly sized type. This will compile to a single instruction
186 // once the IR is converted to assembly if the SIMD instruction is supported
187 // by the target architecture.
188 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
191 /// Retrieve the information we are losing (making dynamic) in an unsizing
194 /// The `old_info` argument is a bit funny. It is intended for use
195 /// in an upcast, where the new vtable for an object will be derived
196 /// from the old one.
197 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
200 old_info: Option<ValueRef>)
202 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
203 match (&source.sty, &target.sty) {
204 (&ty::TyArray(_, len), &ty::TySlice(_)) => {
205 C_usize(ccx, len.val.to_const_int().unwrap().to_u64().unwrap())
207 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
208 // For now, upcasts are limited to changes in marker
209 // traits, and hence never actually require an actual
210 // change to the vtable.
211 old_info.expect("unsized_info: missing old info for trait upcast")
213 (_, &ty::TyDynamic(ref data, ..)) => {
214 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
215 Type::vtable_ptr(ccx))
217 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
223 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
224 pub fn unsize_thin_ptr<'a, 'tcx>(
225 bcx: &Builder<'a, 'tcx>,
229 ) -> (ValueRef, ValueRef) {
230 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
231 match (&src_ty.sty, &dst_ty.sty) {
232 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
233 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
234 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
235 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
236 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
237 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
238 assert!(bcx.ccx.shared().type_is_sized(a));
239 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
240 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
242 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
243 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
244 assert!(bcx.ccx.shared().type_is_sized(a));
245 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
246 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
248 _ => bug!("unsize_thin_ptr: called on bad types"),
252 /// Coerce `src`, which is a reference to a value of type `src_ty`,
253 /// to a value of type `dst_ty` and store the result in `dst`
254 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
255 src: &LvalueRef<'tcx>,
256 dst: &LvalueRef<'tcx>) {
257 let src_ty = src.ty.to_ty(bcx.tcx());
258 let dst_ty = dst.ty.to_ty(bcx.tcx());
259 let coerce_ptr = || {
260 let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
261 // fat-ptr to fat-ptr unsize preserves the vtable
262 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
263 // So we need to pointercast the base to ensure
264 // the types match up.
265 let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
266 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
267 let base = bcx.pointercast(base, llcast_ty);
270 let base = load_ty(bcx, src.llval, src.alignment, src_ty);
271 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
273 store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
275 match (&src_ty.sty, &dst_ty.sty) {
276 (&ty::TyRef(..), &ty::TyRef(..)) |
277 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
278 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
281 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
285 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
286 assert_eq!(def_a, def_b);
288 let src_fields = def_a.variants[0].fields.iter().map(|f| {
289 monomorphize::field_ty(bcx.tcx(), substs_a, f)
291 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
292 monomorphize::field_ty(bcx.tcx(), substs_b, f)
295 let iter = src_fields.zip(dst_fields).enumerate();
296 for (i, (src_fty, dst_fty)) in iter {
297 if type_is_zero_size(bcx.ccx, dst_fty) {
301 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
302 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
303 if src_fty == dst_fty {
304 memcpy_ty(bcx, dst_f, src_f, src_fty, None);
308 &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
309 &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
314 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
320 pub fn cast_shift_expr_rhs(
321 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
323 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
326 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
330 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
331 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
334 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
340 where F: FnOnce(ValueRef, Type) -> ValueRef,
341 G: FnOnce(ValueRef, Type) -> ValueRef
343 // Shifts may have any size int on the rhs
345 let mut rhs_llty = val_ty(rhs);
346 let mut lhs_llty = val_ty(lhs);
347 if rhs_llty.kind() == Vector {
348 rhs_llty = rhs_llty.element_type()
350 if lhs_llty.kind() == Vector {
351 lhs_llty = lhs_llty.element_type()
353 let rhs_sz = rhs_llty.int_width();
354 let lhs_sz = lhs_llty.int_width();
357 } else if lhs_sz > rhs_sz {
358 // FIXME (#1877: If shifting by negative
359 // values becomes not undefined then this is wrong.
369 /// Returns whether this session's target will use SEH-based unwinding.
371 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
372 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
373 /// 64-bit MinGW) instead of "full SEH".
374 pub fn wants_msvc_seh(sess: &Session) -> bool {
375 sess.target.target.options.is_like_msvc
378 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
379 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
380 b.call(assume_intrinsic, &[val], None);
383 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
384 /// differs from the type used for SSA values. Also handles various special cases where the type
385 /// gives us better information about what we are loading.
386 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
387 alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
389 if type_is_zero_size(ccx, t) {
390 return C_undef(type_of::type_of(ccx, t));
394 let global = llvm::LLVMIsAGlobalVariable(ptr);
395 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
396 let val = llvm::LLVMGetInitializer(global);
399 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
407 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
409 } else if t.is_char() {
410 // a char is a Unicode codepoint, and so takes values from 0
411 // to 0x10FFFF inclusive only.
412 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
413 } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
414 && !common::type_is_fat_ptr(ccx, t)
416 b.load_nonnull(ptr, alignment.to_align())
418 b.load(ptr, alignment.to_align())
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: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
425 dst_align: Alignment, t: Ty<'tcx>) {
426 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
428 if common::type_is_fat_ptr(cx.ccx, t) {
429 let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
430 let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
431 store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
433 cx.store(from_immediate(cx, v), dst, dst_align.to_align());
437 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
441 dst_align: Alignment,
443 // FIXME: emit metadata
444 cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
445 cx.store(extra, get_meta(cx, dst), dst_align.to_align());
448 pub fn load_fat_ptr<'a, 'tcx>(
449 b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
450 ) -> (ValueRef, ValueRef) {
451 let ptr = get_dataptr(b, src);
452 let ptr = if t.is_region_ptr() || t.is_box() {
453 b.load_nonnull(ptr, alignment.to_align())
455 b.load(ptr, alignment.to_align())
458 let meta = get_meta(b, src);
459 let meta_ty = val_ty(meta);
460 // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
462 let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
463 b.load_nonnull(meta, None)
471 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
472 if val_ty(val) == Type::i1(bcx.ccx) {
473 bcx.zext(val, Type::i8(bcx.ccx))
479 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
481 bcx.trunc(val, Type::i1(bcx.ccx))
487 pub enum Lifetime { Start, End }
490 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
491 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
492 // and the intrinsic for `lt` and passes them to `emit`, which is in
493 // charge of generating code to call the passed intrinsic on whatever
494 // block of generated code is targeted for the intrinsic.
496 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
497 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
498 pub fn call(self, b: &Builder, ptr: ValueRef) {
499 if b.ccx.sess().opts.optimize == config::OptLevel::No {
503 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
508 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
509 Lifetime::Start => "llvm.lifetime.start",
510 Lifetime::End => "llvm.lifetime.end"
513 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
514 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
518 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
524 let ptr_width = &ccx.sess().target.target.target_pointer_width;
525 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
526 let memcpy = ccx.get_intrinsic(&key);
527 let src_ptr = b.pointercast(src, Type::i8p(ccx));
528 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
529 let size = b.intcast(n_bytes, ccx.isize_ty(), false);
530 let align = C_i32(ccx, align as i32);
531 let volatile = C_bool(ccx, false);
532 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
535 pub fn memcpy_ty<'a, 'tcx>(
536 bcx: &Builder<'a, 'tcx>,
544 let size = ccx.size_of(t);
549 let align = align.unwrap_or_else(|| ccx.align_of(t));
550 call_memcpy(bcx, dst, src, C_usize(ccx, size), align);
553 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
558 volatile: bool) -> ValueRef {
559 let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
560 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
561 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
562 let volatile = C_bool(b.ccx, volatile);
563 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
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_id(), &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 = common::instance_ty(ccx.shared(), &instance);
582 let sig = common::ty_fn_sig(ccx, fn_ty);
583 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
585 let lldecl = match ccx.instances().borrow().get(&instance) {
587 None => bug!("Instance `{:?}` not already declared", instance)
590 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
592 // The `uwtable` attribute according to LLVM is:
594 // This attribute indicates that the ABI being targeted requires that an
595 // unwind table entry be produced for this function even if we can show
596 // that no exceptions passes by it. This is normally the case for the
597 // ELF x86-64 abi, but it can be disabled for some compilation units.
599 // Typically when we're compiling with `-C panic=abort` (which implies this
600 // `no_landing_pads` check) we don't need `uwtable` because we can't
601 // generate any exceptions! On Windows, however, exceptions include other
602 // events such as illegal instructions, segfaults, etc. This means that on
603 // Windows we end up still needing the `uwtable` attribute even if the `-C
604 // panic=abort` flag is passed.
606 // You can also find more info on why Windows is whitelisted here in:
607 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
608 if !ccx.sess().no_landing_pads() ||
609 ccx.sess().target.target.options.is_like_windows {
610 attributes::emit_uwtable(lldecl, true);
613 let mir = ccx.tcx().instance_mir(instance.def);
614 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
617 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
618 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
619 // applicable to variable declarations and may not really make sense for
620 // Rust code in the first place but whitelist them anyway and trust that
621 // the user knows what s/he's doing. Who knows, unanticipated use cases
622 // may pop up in the future.
624 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
625 // and don't have to be, LLVM treats them as no-ops.
627 "appending" => Some(llvm::Linkage::AppendingLinkage),
628 "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
629 "common" => Some(llvm::Linkage::CommonLinkage),
630 "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
631 "external" => Some(llvm::Linkage::ExternalLinkage),
632 "internal" => Some(llvm::Linkage::InternalLinkage),
633 "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
634 "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
635 "private" => Some(llvm::Linkage::PrivateLinkage),
636 "weak" => Some(llvm::Linkage::WeakAnyLinkage),
637 "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
642 pub fn set_link_section(ccx: &CrateContext,
644 attrs: &[ast::Attribute]) {
645 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
646 if contains_null(§.as_str()) {
647 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
650 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
651 llvm::LLVMSetSection(llval, buf.as_ptr());
656 // check for the #[rustc_error] annotation, which forces an
657 // error in trans. This is used to write compile-fail tests
658 // that actually test that compilation succeeds without
659 // reporting an error.
660 fn check_for_rustc_errors_attr(tcx: TyCtxt) {
661 if let Some((id, span)) = *tcx.sess.entry_fn.borrow() {
662 let main_def_id = tcx.hir.local_def_id(id);
664 if tcx.has_attr(main_def_id, "rustc_error") {
665 tcx.sess.span_fatal(span, "compilation successful");
670 /// Create the `main` function which will initialize the rust runtime and call
671 /// users main function.
672 fn maybe_create_entry_wrapper(ccx: &CrateContext) {
673 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
674 Some((id, span)) => {
675 (ccx.tcx().hir.local_def_id(id), span)
680 let instance = Instance::mono(ccx.tcx(), main_def_id);
682 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
683 // We want to create the wrapper in the same codegen unit as Rust's main
688 let main_llfn = callee::get_fn(ccx, instance);
690 let et = ccx.sess().entry_type.get().unwrap();
692 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
693 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
694 config::EntryNone => {} // Do nothing.
697 fn create_entry_fn(ccx: &CrateContext,
700 use_start_lang_item: bool) {
701 let llfty = Type::func(&[ccx.isize_ty(), Type::i8p(ccx).ptr_to()], &ccx.isize_ty());
703 if declare::get_defined_value(ccx, "main").is_some() {
704 // FIXME: We should be smart and show a better diagnostic here.
705 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
706 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
708 ccx.sess().abort_if_errors();
711 let llfn = declare::declare_cfn(ccx, "main", llfty);
713 // `main` should respect same config for frame pointer elimination as rest of code
714 attributes::set_frame_pointer_elimination(ccx, llfn);
716 let bld = Builder::new_block(ccx, llfn, "top");
718 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
720 let (start_fn, args) = if use_start_lang_item {
721 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
722 let start_instance = Instance::mono(ccx.tcx(), start_def_id);
723 let start_fn = callee::get_fn(ccx, start_instance);
724 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
727 debug!("using user-defined start fn");
728 (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
731 let result = bld.call(start_fn, &args, None);
736 fn contains_null(s: &str) -> bool {
737 s.bytes().any(|b| b == 0)
740 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
741 link_meta: &LinkMeta,
742 exported_symbols: &NodeSet)
743 -> (ContextRef, ModuleRef,
744 EncodedMetadata, EncodedMetadataHashes) {
746 use flate2::Compression;
747 use flate2::write::DeflateEncoder;
749 let (metadata_llcx, metadata_llmod) = unsafe {
750 context::create_context_and_module(tcx.sess, "metadata")
753 #[derive(PartialEq, Eq, PartialOrd, Ord)]
760 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
762 config::CrateTypeExecutable |
763 config::CrateTypeStaticlib |
764 config::CrateTypeCdylib => MetadataKind::None,
766 config::CrateTypeRlib => MetadataKind::Uncompressed,
768 config::CrateTypeDylib |
769 config::CrateTypeProcMacro => MetadataKind::Compressed,
773 if kind == MetadataKind::None {
774 return (metadata_llcx,
776 EncodedMetadata::new(),
777 EncodedMetadataHashes::new());
780 let cstore = tcx.cstore_untracked();
781 let (metadata, hashes) = cstore.encode_metadata(tcx,
784 if kind == MetadataKind::Uncompressed {
785 return (metadata_llcx, metadata_llmod, metadata, hashes);
788 assert!(kind == MetadataKind::Compressed);
789 let mut compressed = cstore.metadata_encoding_version().to_vec();
790 DeflateEncoder::new(&mut compressed, Compression::Fast)
791 .write_all(&metadata.raw_data).unwrap();
793 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
794 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
795 let name = symbol_export::metadata_symbol_name(tcx);
796 let buf = CString::new(name).unwrap();
797 let llglobal = unsafe {
798 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
801 llvm::LLVMSetInitializer(llglobal, llconst);
802 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
803 let name = CString::new(section_name).unwrap();
804 llvm::LLVMSetSection(llglobal, name.as_ptr());
806 // Also generate a .section directive to force no
807 // flags, at least for ELF outputs, so that the
808 // metadata doesn't get loaded into memory.
809 let directive = format!(".section {}", section_name);
810 let directive = CString::new(directive).unwrap();
811 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
813 return (metadata_llcx, metadata_llmod, metadata, hashes);
816 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
817 // This is required to satisfy `dllimport` references to static data in .rlibs
818 // when using MSVC linker. We do this only for data, as linker can fix up
819 // code references on its own.
820 // See #26591, #27438
821 fn create_imps(sess: &Session,
822 llvm_module: &ModuleLlvm) {
823 // The x86 ABI seems to require that leading underscores are added to symbol
824 // names, so we need an extra underscore on 32-bit. There's also a leading
825 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
826 // underscores added in front).
827 let prefix = if sess.target.target.target_pointer_width == "32" {
833 let exported: Vec<_> = iter_globals(llvm_module.llmod)
835 llvm::LLVMRustGetLinkage(val) ==
836 llvm::Linkage::ExternalLinkage &&
837 llvm::LLVMIsDeclaration(val) == 0
841 let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
842 for val in exported {
843 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
844 let mut imp_name = prefix.as_bytes().to_vec();
845 imp_name.extend(name.to_bytes());
846 let imp_name = CString::new(imp_name).unwrap();
847 let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
849 imp_name.as_ptr() as *const _);
850 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
851 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
858 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
861 impl Iterator for ValueIter {
862 type Item = ValueRef;
864 fn next(&mut self) -> Option<ValueRef> {
867 self.cur = unsafe { (self.step)(old) };
875 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
878 cur: llvm::LLVMGetFirstGlobal(llmod),
879 step: llvm::LLVMGetNextGlobal,
884 /// The context provided lists a set of reachable ids as calculated by
885 /// middle::reachable, but this contains far more ids and symbols than we're
886 /// actually exposing from the object file. This function will filter the set in
887 /// the context to the set of ids which correspond to symbols that are exposed
888 /// from the object file being generated.
890 /// This list is later used by linkers to determine the set of symbols needed to
891 /// be exposed from a dynamic library and it's also encoded into the metadata.
892 pub fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet {
893 reachable.iter().cloned().filter(|&id| {
894 // Next, we want to ignore some FFI functions that are not exposed from
895 // this crate. Reachable FFI functions can be lumped into two
898 // 1. Those that are included statically via a static library
899 // 2. Those included otherwise (e.g. dynamically or via a framework)
901 // Although our LLVM module is not literally emitting code for the
902 // statically included symbols, it's an export of our library which
903 // needs to be passed on to the linker and encoded in the metadata.
905 // As a result, if this id is an FFI item (foreign item) then we only
906 // let it through if it's included statically.
907 match tcx.hir.get(id) {
908 hir_map::NodeForeignItem(..) => {
909 let def_id = tcx.hir.local_def_id(id);
910 tcx.is_statically_included_foreign_item(def_id)
913 // Only consider nodes that actually have exported symbols.
914 hir_map::NodeItem(&hir::Item {
915 node: hir::ItemStatic(..), .. }) |
916 hir_map::NodeItem(&hir::Item {
917 node: hir::ItemFn(..), .. }) |
918 hir_map::NodeImplItem(&hir::ImplItem {
919 node: hir::ImplItemKind::Method(..), .. }) => {
920 let def_id = tcx.hir.local_def_id(id);
921 let generics = tcx.generics_of(def_id);
922 let attributes = tcx.get_attrs(def_id);
923 (generics.parent_types == 0 && generics.types.is_empty()) &&
924 // Functions marked with #[inline] are only ever translated
925 // with "internal" linkage and are never exported.
926 !attr::requests_inline(&attributes)
934 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
935 analysis: ty::CrateAnalysis,
936 incremental_hashes_map: IncrementalHashesMap,
937 output_filenames: &OutputFilenames)
938 -> OngoingCrateTranslation {
939 check_for_rustc_errors_attr(tcx);
941 // Be careful with this krate: obviously it gives access to the
942 // entire contents of the krate. So if you push any subtasks of
943 // `TransCrate`, you need to be careful to register "reads" of the
944 // particular items that will be processed.
945 let krate = tcx.hir.krate();
946 let ty::CrateAnalysis { reachable, .. } = analysis;
947 let check_overflow = tcx.sess.overflow_checks();
948 let link_meta = link::build_link_meta(&incremental_hashes_map);
949 let exported_symbol_node_ids = find_exported_symbols(tcx, &reachable);
951 let shared_ccx = SharedCrateContext::new(tcx,
954 // Translate the metadata.
955 let (metadata_llcx, metadata_llmod, metadata, metadata_incr_hashes) =
956 time(tcx.sess.time_passes(), "write metadata", || {
957 write_metadata(tcx, &link_meta, &exported_symbol_node_ids)
960 let metadata_module = ModuleTranslation {
961 name: link::METADATA_MODULE_NAME.to_string(),
962 symbol_name_hash: 0, // we always rebuild metadata, at least for now
963 source: ModuleSource::Translated(ModuleLlvm {
965 llmod: metadata_llmod,
967 kind: ModuleKind::Metadata,
970 let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
971 let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
972 Some(time_graph::TimeGraph::new())
976 let crate_info = CrateInfo::new(tcx);
978 // Skip crate items and just output metadata in -Z no-trans mode.
979 if tcx.sess.opts.debugging_opts.no_trans ||
980 !tcx.sess.opts.output_types.should_trans() {
981 let empty_exported_symbols = ExportedSymbols::empty();
982 let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
983 let ongoing_translation = write::start_async_translation(
987 tcx.crate_name(LOCAL_CRATE),
990 Arc::new(empty_exported_symbols),
997 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, metadata_module, true);
999 assert_and_save_dep_graph(tcx,
1000 incremental_hashes_map,
1001 metadata_incr_hashes,
1004 ongoing_translation.check_for_errors(tcx.sess);
1006 return ongoing_translation;
1009 let exported_symbols = Arc::new(ExportedSymbols::compute(tcx,
1010 &exported_symbol_node_ids));
1012 // Run the translation item collector and partition the collected items into
1014 let (translation_items, codegen_units) =
1015 collect_and_partition_translation_items(&shared_ccx, &exported_symbols);
1017 assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
1019 let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1020 let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1021 "windows_subsystem");
1022 let windows_subsystem = subsystem.map(|subsystem| {
1023 if subsystem != "windows" && subsystem != "console" {
1024 tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1025 `windows` and `console` are allowed",
1028 subsystem.to_string()
1031 let no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1032 (tcx.sess.target.target.options.no_integrated_as &&
1033 (output_filenames.outputs.contains_key(&OutputType::Object) ||
1034 output_filenames.outputs.contains_key(&OutputType::Exe)));
1036 let ongoing_translation = write::start_async_translation(
1040 tcx.crate_name(LOCAL_CRATE),
1043 exported_symbols.clone(),
1050 // Translate an allocator shim, if any
1052 // If LTO is enabled and we've got some previous LLVM module we translated
1053 // above, then we can just translate directly into that LLVM module. If not,
1054 // however, we need to create a separate module and trans into that. Note
1055 // that the separate translation is critical for the standard library where
1056 // the rlib's object file doesn't have allocator functions but the dylib
1057 // links in an object file that has allocator functions. When we're
1058 // compiling a final LTO artifact, though, there's no need to worry about
1059 // this as we're not working with this dual "rlib/dylib" functionality.
1060 let allocator_module = if tcx.sess.lto() {
1062 } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1065 context::create_context_and_module(tcx.sess, "allocator");
1066 let modules = ModuleLlvm {
1070 time(tcx.sess.time_passes(), "write allocator module", || {
1071 allocator::trans(tcx, &modules, kind)
1074 Some(ModuleTranslation {
1075 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1076 symbol_name_hash: 0, // we always rebuild allocator shims
1077 source: ModuleSource::Translated(modules),
1078 kind: ModuleKind::Allocator,
1085 if let Some(allocator_module) = allocator_module {
1086 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, allocator_module, false);
1089 let codegen_unit_count = codegen_units.len();
1090 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess,
1092 codegen_unit_count == 0);
1094 let translation_items = Arc::new(translation_items);
1096 let mut all_stats = Stats::default();
1097 let mut module_dispositions = tcx.sess.opts.incremental.as_ref().map(|_| Vec::new());
1099 // We sort the codegen units by size. This way we can schedule work for LLVM
1100 // a bit more efficiently. Note that "size" is defined rather crudely at the
1101 // moment as it is just the number of TransItems in the CGU, not taking into
1102 // account the size of each TransItem.
1103 let codegen_units = {
1104 let mut codegen_units = codegen_units;
1105 codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
1109 let mut total_trans_time = Duration::new(0, 0);
1111 for (cgu_index, cgu) in codegen_units.into_iter().enumerate() {
1112 ongoing_translation.wait_for_signal_to_translate_item();
1113 ongoing_translation.check_for_errors(tcx.sess);
1115 let start_time = Instant::now();
1118 let _timing_guard = time_graph
1120 .map(|time_graph| time_graph.start(write::TRANS_WORKER_TIMELINE,
1121 write::TRANS_WORK_PACKAGE_KIND));
1122 let dep_node = cgu.work_product_dep_node();
1123 let ((stats, module), _) =
1124 tcx.dep_graph.with_task(dep_node,
1125 AssertDepGraphSafe(&shared_ccx),
1126 AssertDepGraphSafe((cgu,
1127 translation_items.clone(),
1128 exported_symbols.clone())),
1129 module_translation);
1130 all_stats.extend(stats);
1132 if let Some(ref mut module_dispositions) = module_dispositions {
1133 module_dispositions.push(module.disposition());
1139 let time_to_translate = Instant::now().duration_since(start_time);
1141 // We assume that the cost to run LLVM on a CGU is proportional to
1142 // the time we needed for translating it.
1143 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1144 time_to_translate.subsec_nanos() as u64;
1146 total_trans_time += time_to_translate;
1148 let is_last_cgu = (cgu_index + 1) == codegen_unit_count;
1150 ongoing_translation.submit_translated_module_to_llvm(tcx.sess,
1154 ongoing_translation.check_for_errors(tcx.sess);
1157 // Since the main thread is sometimes blocked during trans, we keep track
1158 // -Ztime-passes output manually.
1159 print_time_passes_entry(tcx.sess.time_passes(),
1160 "translate to LLVM IR",
1163 if let Some(module_dispositions) = module_dispositions {
1164 assert_module_sources::assert_module_sources(tcx, &module_dispositions);
1167 fn module_translation<'a, 'tcx>(
1168 scx: AssertDepGraphSafe<&SharedCrateContext<'a, 'tcx>>,
1169 args: AssertDepGraphSafe<(CodegenUnit<'tcx>,
1170 Arc<FxHashSet<TransItem<'tcx>>>,
1171 Arc<ExportedSymbols>)>)
1172 -> (Stats, ModuleTranslation)
1174 // FIXME(#40304): We ought to be using the id as a key and some queries, I think.
1175 let AssertDepGraphSafe(scx) = scx;
1176 let AssertDepGraphSafe((cgu, crate_trans_items, exported_symbols)) = args;
1178 let cgu_name = String::from(cgu.name());
1179 let cgu_id = cgu.work_product_id();
1180 let symbol_name_hash = cgu.compute_symbol_name_hash(scx);
1182 // Check whether there is a previous work-product we can
1183 // re-use. Not only must the file exist, and the inputs not
1184 // be dirty, but the hash of the symbols we will generate must
1186 let previous_work_product =
1187 scx.dep_graph().previous_work_product(&cgu_id).and_then(|work_product| {
1188 if work_product.input_hash == symbol_name_hash {
1189 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1192 if scx.sess().opts.debugging_opts.incremental_info {
1193 eprintln!("incremental: CGU `{}` invalidated because of \
1194 changed partitioning hash.",
1197 debug!("trans_reuse_previous_work_products: \
1198 not reusing {:?} because hash changed to {:?}",
1199 work_product, symbol_name_hash);
1204 if let Some(buf) = previous_work_product {
1205 // Don't need to translate this module.
1206 let module = ModuleTranslation {
1209 source: ModuleSource::Preexisting(buf.clone()),
1210 kind: ModuleKind::Regular,
1212 return (Stats::default(), module);
1215 // Instantiate translation items without filling out definitions yet...
1216 let lcx = LocalCrateContext::new(scx, cgu, crate_trans_items, exported_symbols);
1218 let ccx = CrateContext::new(scx, &lcx);
1219 let trans_items = ccx.codegen_unit()
1220 .items_in_deterministic_order(ccx.tcx());
1221 for &(trans_item, (linkage, visibility)) in &trans_items {
1222 trans_item.predefine(&ccx, linkage, visibility);
1225 // ... and now that we have everything pre-defined, fill out those definitions.
1226 for &(trans_item, _) in &trans_items {
1227 trans_item.define(&ccx);
1230 // If this codegen unit contains the main function, also create the
1232 maybe_create_entry_wrapper(&ccx);
1234 // Run replace-all-uses-with for statics that need it
1235 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1237 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1238 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1239 llvm::LLVMDeleteGlobal(old_g);
1243 // Create the llvm.used variable
1244 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1245 if !ccx.used_statics().borrow().is_empty() {
1246 let name = CString::new("llvm.used").unwrap();
1247 let section = CString::new("llvm.metadata").unwrap();
1248 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1251 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1252 val_ty(array).to_ref(),
1254 llvm::LLVMSetInitializer(g, array);
1255 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1256 llvm::LLVMSetSection(g, section.as_ptr());
1260 // Finalize debuginfo
1261 if ccx.sess().opts.debuginfo != NoDebugInfo {
1262 debuginfo::finalize(&ccx);
1265 let llvm_module = ModuleLlvm {
1270 // In LTO mode we inject the allocator shim into the existing
1272 if ccx.sess().lto() {
1273 if let Some(kind) = ccx.sess().allocator_kind.get() {
1274 time(ccx.sess().time_passes(), "write allocator module", || {
1276 allocator::trans(ccx.tcx(), &llvm_module, kind);
1282 // Adjust exported symbols for MSVC dllimport
1283 if ccx.sess().target.target.options.is_like_msvc &&
1284 ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1285 create_imps(ccx.sess(), &llvm_module);
1291 source: ModuleSource::Translated(llvm_module),
1292 kind: ModuleKind::Regular,
1296 (lcx.into_stats(), module)
1299 symbol_names_test::report_symbol_names(tcx);
1301 if shared_ccx.sess().trans_stats() {
1302 println!("--- trans stats ---");
1303 println!("n_glues_created: {}", all_stats.n_glues_created.get());
1304 println!("n_null_glues: {}", all_stats.n_null_glues.get());
1305 println!("n_real_glues: {}", all_stats.n_real_glues.get());
1307 println!("n_fns: {}", all_stats.n_fns.get());
1308 println!("n_inlines: {}", all_stats.n_inlines.get());
1309 println!("n_closures: {}", all_stats.n_closures.get());
1310 println!("fn stats:");
1311 all_stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1312 insns_b.cmp(&insns_a)
1314 for tuple in all_stats.fn_stats.borrow().iter() {
1316 (ref name, insns) => {
1317 println!("{} insns, {}", insns, *name);
1323 if shared_ccx.sess().count_llvm_insns() {
1324 for (k, v) in all_stats.llvm_insns.borrow().iter() {
1325 println!("{:7} {}", *v, *k);
1329 ongoing_translation.check_for_errors(tcx.sess);
1331 assert_and_save_dep_graph(tcx,
1332 incremental_hashes_map,
1333 metadata_incr_hashes,
1338 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1339 incremental_hashes_map: IncrementalHashesMap,
1340 metadata_incr_hashes: EncodedMetadataHashes,
1341 link_meta: LinkMeta) {
1342 time(tcx.sess.time_passes(),
1344 || rustc_incremental::assert_dep_graph(tcx));
1346 time(tcx.sess.time_passes(),
1347 "serialize dep graph",
1348 || rustc_incremental::save_dep_graph(tcx,
1349 incremental_hashes_map,
1350 &metadata_incr_hashes,
1351 link_meta.crate_hash));
1354 #[inline(never)] // give this a place in the profiler
1355 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1356 where I: Iterator<Item=&'a TransItem<'tcx>>
1358 let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1359 (trans_item, trans_item.symbol_name(tcx))
1362 (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1366 for pair in (&symbols[..]).windows(2) {
1367 let sym1 = &pair[0].1;
1368 let sym2 = &pair[1].1;
1371 let trans_item1 = pair[0].0;
1372 let trans_item2 = pair[1].0;
1374 let span1 = trans_item1.local_span(tcx);
1375 let span2 = trans_item2.local_span(tcx);
1377 // Deterministically select one of the spans for error reporting
1378 let span = match (span1, span2) {
1379 (Some(span1), Some(span2)) => {
1380 Some(if span1.lo().0 > span2.lo().0 {
1386 (Some(span), None) |
1387 (None, Some(span)) => Some(span),
1391 let error_message = format!("symbol `{}` is already defined", sym1);
1393 if let Some(span) = span {
1394 tcx.sess.span_fatal(span, &error_message)
1396 tcx.sess.fatal(&error_message)
1402 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
1403 exported_symbols: &ExportedSymbols)
1404 -> (FxHashSet<TransItem<'tcx>>,
1405 Vec<CodegenUnit<'tcx>>) {
1406 let time_passes = scx.sess().time_passes();
1408 let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1410 let mode_string = s.to_lowercase();
1411 let mode_string = mode_string.trim();
1412 if mode_string == "eager" {
1413 TransItemCollectionMode::Eager
1415 if mode_string != "lazy" {
1416 let message = format!("Unknown codegen-item collection mode '{}'. \
1417 Falling back to 'lazy' mode.",
1419 scx.sess().warn(&message);
1422 TransItemCollectionMode::Lazy
1425 None => TransItemCollectionMode::Lazy
1428 let (items, inlining_map) =
1429 time(time_passes, "translation item collection", || {
1430 collector::collect_crate_translation_items(&scx,
1435 assert_symbols_are_distinct(scx.tcx(), items.iter());
1437 let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1438 PartitioningStrategy::PerModule
1440 PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1443 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1444 partitioning::partition(scx,
1445 items.iter().cloned(),
1451 assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1452 scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1454 let translation_items: FxHashSet<TransItem<'tcx>> = items.iter().cloned().collect();
1456 if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1457 let mut item_to_cgus = FxHashMap();
1459 for cgu in &codegen_units {
1460 for (&trans_item, &linkage) in cgu.items() {
1461 item_to_cgus.entry(trans_item)
1462 .or_insert(Vec::new())
1463 .push((cgu.name().clone(), linkage));
1467 let mut item_keys: Vec<_> = items
1470 let mut output = i.to_string(scx.tcx());
1471 output.push_str(" @@");
1472 let mut empty = Vec::new();
1473 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1474 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1476 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1477 output.push_str(" ");
1478 output.push_str(&cgu_name);
1480 let linkage_abbrev = match linkage {
1481 llvm::Linkage::ExternalLinkage => "External",
1482 llvm::Linkage::AvailableExternallyLinkage => "Available",
1483 llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1484 llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1485 llvm::Linkage::WeakAnyLinkage => "WeakAny",
1486 llvm::Linkage::WeakODRLinkage => "WeakODR",
1487 llvm::Linkage::AppendingLinkage => "Appending",
1488 llvm::Linkage::InternalLinkage => "Internal",
1489 llvm::Linkage::PrivateLinkage => "Private",
1490 llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1491 llvm::Linkage::CommonLinkage => "Common",
1494 output.push_str("[");
1495 output.push_str(linkage_abbrev);
1496 output.push_str("]");
1504 for item in item_keys {
1505 println!("TRANS_ITEM {}", item);
1509 (translation_items, codegen_units)
1513 pub fn new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CrateInfo {
1514 let mut info = CrateInfo {
1515 panic_runtime: None,
1516 compiler_builtins: None,
1517 profiler_runtime: None,
1518 sanitizer_runtime: None,
1519 is_no_builtins: FxHashSet(),
1520 native_libraries: FxHashMap(),
1521 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1522 link_args: tcx.link_args(LOCAL_CRATE),
1523 crate_name: FxHashMap(),
1524 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1525 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1526 used_crate_source: FxHashMap(),
1529 for &cnum in tcx.crates().iter() {
1530 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1531 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1532 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1533 if tcx.is_panic_runtime(cnum) {
1534 info.panic_runtime = Some(cnum);
1536 if tcx.is_compiler_builtins(cnum) {
1537 info.compiler_builtins = Some(cnum);
1539 if tcx.is_profiler_runtime(cnum) {
1540 info.profiler_runtime = Some(cnum);
1542 if tcx.is_sanitizer_runtime(cnum) {
1543 info.sanitizer_runtime = Some(cnum);
1545 if tcx.is_no_builtins(cnum) {
1546 info.is_no_builtins.insert(cnum);