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;
35 use back::write::{self, OngoingCrateTranslation};
36 use llvm::{ContextRef, ModuleRef, ValueRef, Vector, get_param};
39 use rustc::hir::def_id::{CrateNum, LOCAL_CRATE};
40 use rustc::middle::lang_items::StartFnLangItem;
41 use rustc::middle::trans::{Linkage, Visibility};
42 use rustc::middle::cstore::{EncodedMetadata, EncodedMetadataHashes};
43 use rustc::ty::{self, Ty, TyCtxt};
44 use rustc::ty::maps::Providers;
45 use rustc::dep_graph::AssertDepGraphSafe;
46 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
47 use rustc::middle::exported_symbols::ExportedSymbols;
48 use rustc::hir::map as hir_map;
49 use rustc::util::common::{time, print_time_passes_entry};
50 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType};
51 use rustc::session::Session;
52 use rustc_incremental::{self, IncrementalHashesMap};
55 use mir::lvalue::LvalueRef;
59 use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
60 use collector::{self, TransItemCollectionMode};
61 use common::{C_struct_in_context, C_u64, C_undef, C_array};
62 use common::CrateContext;
63 use common::{type_is_zero_size, val_ty};
66 use context::{self, LocalCrateContext, SharedCrateContext, Stats};
72 use monomorphize::{self, Instance};
73 use partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
74 use symbol_names_test;
76 use trans_item::{TransItem, TransItemExt, DefPathBasedNames};
80 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet};
84 use std::ffi::{CStr, CString};
87 use std::time::{Instant, Duration};
94 use mir::lvalue::Alignment;
96 pub struct StatRecorder<'a, 'tcx: 'a> {
97 ccx: &'a CrateContext<'a, 'tcx>,
102 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
103 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
104 let istart = ccx.stats().n_llvm_insns.get();
113 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
115 if self.ccx.sess().trans_stats() {
116 let iend = self.ccx.stats().n_llvm_insns.get();
117 self.ccx.stats().fn_stats.borrow_mut()
118 .push((self.name.take().unwrap(), iend - self.istart));
119 self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
120 // Reset LLVM insn count to avoid compound costs.
121 self.ccx.stats().n_llvm_insns.set(self.istart);
126 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
127 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
130 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
131 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
134 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
136 -> llvm::IntPredicate {
138 hir::BiEq => llvm::IntEQ,
139 hir::BiNe => llvm::IntNE,
140 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
141 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
142 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
143 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
145 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
152 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
154 hir::BiEq => llvm::RealOEQ,
155 hir::BiNe => llvm::RealUNE,
156 hir::BiLt => llvm::RealOLT,
157 hir::BiLe => llvm::RealOLE,
158 hir::BiGt => llvm::RealOGT,
159 hir::BiGe => llvm::RealOGE,
161 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
168 pub fn compare_simd_types<'a, 'tcx>(
169 bcx: &Builder<'a, 'tcx>,
176 let signed = match t.sty {
178 let cmp = bin_op_to_fcmp_predicate(op);
179 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
181 ty::TyUint(_) => false,
182 ty::TyInt(_) => true,
183 _ => bug!("compare_simd_types: invalid SIMD type"),
186 let cmp = bin_op_to_icmp_predicate(op, signed);
187 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
188 // to get the correctly sized type. This will compile to a single instruction
189 // once the IR is converted to assembly if the SIMD instruction is supported
190 // by the target architecture.
191 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
194 /// Retrieve the information we are losing (making dynamic) in an unsizing
197 /// The `old_info` argument is a bit funny. It is intended for use
198 /// in an upcast, where the new vtable for an object will be derived
199 /// from the old one.
200 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
203 old_info: Option<ValueRef>)
205 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
206 match (&source.sty, &target.sty) {
207 (&ty::TyArray(_, len), &ty::TySlice(_)) => {
208 C_usize(ccx, len.val.to_const_int().unwrap().to_u64().unwrap())
210 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
211 // For now, upcasts are limited to changes in marker
212 // traits, and hence never actually require an actual
213 // change to the vtable.
214 old_info.expect("unsized_info: missing old info for trait upcast")
216 (_, &ty::TyDynamic(ref data, ..)) => {
217 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
218 Type::vtable_ptr(ccx))
220 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
226 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
227 pub fn unsize_thin_ptr<'a, 'tcx>(
228 bcx: &Builder<'a, 'tcx>,
232 ) -> (ValueRef, ValueRef) {
233 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
234 match (&src_ty.sty, &dst_ty.sty) {
235 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
236 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
237 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
238 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
239 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
240 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
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 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
246 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
247 assert!(bcx.ccx.shared().type_is_sized(a));
248 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
249 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
251 _ => bug!("unsize_thin_ptr: called on bad types"),
255 /// Coerce `src`, which is a reference to a value of type `src_ty`,
256 /// to a value of type `dst_ty` and store the result in `dst`
257 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
258 src: &LvalueRef<'tcx>,
259 dst: &LvalueRef<'tcx>) {
260 let src_ty = src.ty.to_ty(bcx.tcx());
261 let dst_ty = dst.ty.to_ty(bcx.tcx());
262 let coerce_ptr = || {
263 let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
264 // fat-ptr to fat-ptr unsize preserves the vtable
265 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
266 // So we need to pointercast the base to ensure
267 // the types match up.
268 let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
269 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
270 let base = bcx.pointercast(base, llcast_ty);
273 let base = load_ty(bcx, src.llval, src.alignment, src_ty);
274 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
276 store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
278 match (&src_ty.sty, &dst_ty.sty) {
279 (&ty::TyRef(..), &ty::TyRef(..)) |
280 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
281 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
284 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
288 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
289 assert_eq!(def_a, def_b);
291 let src_fields = def_a.variants[0].fields.iter().map(|f| {
292 monomorphize::field_ty(bcx.tcx(), substs_a, f)
294 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
295 monomorphize::field_ty(bcx.tcx(), substs_b, f)
298 let iter = src_fields.zip(dst_fields).enumerate();
299 for (i, (src_fty, dst_fty)) in iter {
300 if type_is_zero_size(bcx.ccx, dst_fty) {
304 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
305 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
306 if src_fty == dst_fty {
307 memcpy_ty(bcx, dst_f, src_f, src_fty, None);
311 &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
312 &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
317 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
323 pub fn cast_shift_expr_rhs(
324 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
326 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
329 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
333 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
334 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
337 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
343 where F: FnOnce(ValueRef, Type) -> ValueRef,
344 G: FnOnce(ValueRef, Type) -> ValueRef
346 // Shifts may have any size int on the rhs
348 let mut rhs_llty = val_ty(rhs);
349 let mut lhs_llty = val_ty(lhs);
350 if rhs_llty.kind() == Vector {
351 rhs_llty = rhs_llty.element_type()
353 if lhs_llty.kind() == Vector {
354 lhs_llty = lhs_llty.element_type()
356 let rhs_sz = rhs_llty.int_width();
357 let lhs_sz = lhs_llty.int_width();
360 } else if lhs_sz > rhs_sz {
361 // FIXME (#1877: If shifting by negative
362 // values becomes not undefined then this is wrong.
372 /// Returns whether this session's target will use SEH-based unwinding.
374 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
375 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
376 /// 64-bit MinGW) instead of "full SEH".
377 pub fn wants_msvc_seh(sess: &Session) -> bool {
378 sess.target.target.options.is_like_msvc
381 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
382 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
383 b.call(assume_intrinsic, &[val], None);
386 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
387 /// differs from the type used for SSA values. Also handles various special cases where the type
388 /// gives us better information about what we are loading.
389 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
390 alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
392 if type_is_zero_size(ccx, t) {
393 return C_undef(type_of::type_of(ccx, t));
397 let global = llvm::LLVMIsAGlobalVariable(ptr);
398 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
399 let val = llvm::LLVMGetInitializer(global);
402 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
410 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
412 } else if t.is_char() {
413 // a char is a Unicode codepoint, and so takes values from 0
414 // to 0x10FFFF inclusive only.
415 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
416 } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
417 && !common::type_is_fat_ptr(ccx, t)
419 b.load_nonnull(ptr, alignment.to_align())
421 b.load(ptr, alignment.to_align())
425 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
426 /// differs from the type used for SSA values.
427 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
428 dst_align: Alignment, t: Ty<'tcx>) {
429 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
431 if common::type_is_fat_ptr(cx.ccx, t) {
432 let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
433 let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
434 store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
436 cx.store(from_immediate(cx, v), dst, dst_align.to_align());
440 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
444 dst_align: Alignment,
446 // FIXME: emit metadata
447 cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
448 cx.store(extra, get_meta(cx, dst), dst_align.to_align());
451 pub fn load_fat_ptr<'a, 'tcx>(
452 b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
453 ) -> (ValueRef, ValueRef) {
454 let ptr = get_dataptr(b, src);
455 let ptr = if t.is_region_ptr() || t.is_box() {
456 b.load_nonnull(ptr, alignment.to_align())
458 b.load(ptr, alignment.to_align())
461 let meta = get_meta(b, src);
462 let meta_ty = val_ty(meta);
463 // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
465 let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
466 b.load_nonnull(meta, None)
474 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
475 if val_ty(val) == Type::i1(bcx.ccx) {
476 bcx.zext(val, Type::i8(bcx.ccx))
482 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
484 bcx.trunc(val, Type::i1(bcx.ccx))
490 pub enum Lifetime { Start, End }
493 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
494 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
495 // and the intrinsic for `lt` and passes them to `emit`, which is in
496 // charge of generating code to call the passed intrinsic on whatever
497 // block of generated code is targeted for the intrinsic.
499 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
500 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
501 pub fn call(self, b: &Builder, ptr: ValueRef) {
502 if b.ccx.sess().opts.optimize == config::OptLevel::No {
506 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
511 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
512 Lifetime::Start => "llvm.lifetime.start",
513 Lifetime::End => "llvm.lifetime.end"
516 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
517 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
521 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
527 let ptr_width = &ccx.sess().target.target.target_pointer_width;
528 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
529 let memcpy = ccx.get_intrinsic(&key);
530 let src_ptr = b.pointercast(src, Type::i8p(ccx));
531 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
532 let size = b.intcast(n_bytes, ccx.isize_ty(), false);
533 let align = C_i32(ccx, align as i32);
534 let volatile = C_bool(ccx, false);
535 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
538 pub fn memcpy_ty<'a, 'tcx>(
539 bcx: &Builder<'a, 'tcx>,
547 let size = ccx.size_of(t);
552 let align = align.unwrap_or_else(|| ccx.align_of(t));
553 call_memcpy(bcx, dst, src, C_usize(ccx, size), align);
556 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
561 volatile: bool) -> ValueRef {
562 let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
563 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
564 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
565 let volatile = C_bool(b.ccx, volatile);
566 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
569 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
570 let _s = if ccx.sess().trans_stats() {
571 let mut instance_name = String::new();
572 DefPathBasedNames::new(ccx.tcx(), true, true)
573 .push_def_path(instance.def_id(), &mut instance_name);
574 Some(StatRecorder::new(ccx, instance_name))
579 // this is an info! to allow collecting monomorphization statistics
580 // and to allow finding the last function before LLVM aborts from
582 info!("trans_instance({})", instance);
584 let fn_ty = common::instance_ty(ccx.tcx(), &instance);
585 let sig = common::ty_fn_sig(ccx, fn_ty);
586 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
588 let lldecl = match ccx.instances().borrow().get(&instance) {
590 None => bug!("Instance `{:?}` not already declared", instance)
593 ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
595 // The `uwtable` attribute according to LLVM is:
597 // This attribute indicates that the ABI being targeted requires that an
598 // unwind table entry be produced for this function even if we can show
599 // that no exceptions passes by it. This is normally the case for the
600 // ELF x86-64 abi, but it can be disabled for some compilation units.
602 // Typically when we're compiling with `-C panic=abort` (which implies this
603 // `no_landing_pads` check) we don't need `uwtable` because we can't
604 // generate any exceptions! On Windows, however, exceptions include other
605 // events such as illegal instructions, segfaults, etc. This means that on
606 // Windows we end up still needing the `uwtable` attribute even if the `-C
607 // panic=abort` flag is passed.
609 // You can also find more info on why Windows is whitelisted here in:
610 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
611 if !ccx.sess().no_landing_pads() ||
612 ccx.sess().target.target.options.is_like_windows {
613 attributes::emit_uwtable(lldecl, true);
616 let mir = ccx.tcx().instance_mir(instance.def);
617 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
620 pub fn linkage_by_name(name: &str) -> Option<Linkage> {
621 use rustc::middle::trans::Linkage::*;
623 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
624 // applicable to variable declarations and may not really make sense for
625 // Rust code in the first place but whitelist them anyway and trust that
626 // the user knows what s/he's doing. Who knows, unanticipated use cases
627 // may pop up in the future.
629 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
630 // and don't have to be, LLVM treats them as no-ops.
632 "appending" => Some(Appending),
633 "available_externally" => Some(AvailableExternally),
634 "common" => Some(Common),
635 "extern_weak" => Some(ExternalWeak),
636 "external" => Some(External),
637 "internal" => Some(Internal),
638 "linkonce" => Some(LinkOnceAny),
639 "linkonce_odr" => Some(LinkOnceODR),
640 "private" => Some(Private),
641 "weak" => Some(WeakAny),
642 "weak_odr" => Some(WeakODR),
647 pub fn set_link_section(ccx: &CrateContext,
649 attrs: &[ast::Attribute]) {
650 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
651 if contains_null(§.as_str()) {
652 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
655 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
656 llvm::LLVMSetSection(llval, buf.as_ptr());
661 // check for the #[rustc_error] annotation, which forces an
662 // error in trans. This is used to write compile-fail tests
663 // that actually test that compilation succeeds without
664 // reporting an error.
665 fn check_for_rustc_errors_attr(tcx: TyCtxt) {
666 if let Some((id, span)) = *tcx.sess.entry_fn.borrow() {
667 let main_def_id = tcx.hir.local_def_id(id);
669 if tcx.has_attr(main_def_id, "rustc_error") {
670 tcx.sess.span_fatal(span, "compilation successful");
675 /// Create the `main` function which will initialize the rust runtime and call
676 /// users main function.
677 fn maybe_create_entry_wrapper(ccx: &CrateContext) {
678 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
679 Some((id, span)) => {
680 (ccx.tcx().hir.local_def_id(id), span)
685 let instance = Instance::mono(ccx.tcx(), main_def_id);
687 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
688 // We want to create the wrapper in the same codegen unit as Rust's main
693 let main_llfn = callee::get_fn(ccx, instance);
695 let et = ccx.sess().entry_type.get().unwrap();
697 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
698 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
699 config::EntryNone => {} // Do nothing.
702 fn create_entry_fn(ccx: &CrateContext,
705 use_start_lang_item: bool) {
706 let llfty = Type::func(&[ccx.isize_ty(), Type::i8p(ccx).ptr_to()], &ccx.isize_ty());
708 if declare::get_defined_value(ccx, "main").is_some() {
709 // FIXME: We should be smart and show a better diagnostic here.
710 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
711 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
713 ccx.sess().abort_if_errors();
716 let llfn = declare::declare_cfn(ccx, "main", llfty);
718 // `main` should respect same config for frame pointer elimination as rest of code
719 attributes::set_frame_pointer_elimination(ccx, llfn);
721 let bld = Builder::new_block(ccx, llfn, "top");
723 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
725 let (start_fn, args) = if use_start_lang_item {
726 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
727 let start_instance = Instance::mono(ccx.tcx(), start_def_id);
728 let start_fn = callee::get_fn(ccx, start_instance);
729 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
732 debug!("using user-defined start fn");
733 (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
736 let result = bld.call(start_fn, &args, None);
741 fn contains_null(s: &str) -> bool {
742 s.bytes().any(|b| b == 0)
745 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
746 link_meta: &LinkMeta,
747 exported_symbols: &NodeSet)
748 -> (ContextRef, ModuleRef,
749 EncodedMetadata, EncodedMetadataHashes) {
751 use flate2::Compression;
752 use flate2::write::DeflateEncoder;
754 let (metadata_llcx, metadata_llmod) = unsafe {
755 context::create_context_and_module(tcx.sess, "metadata")
758 #[derive(PartialEq, Eq, PartialOrd, Ord)]
765 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
767 config::CrateTypeExecutable |
768 config::CrateTypeStaticlib |
769 config::CrateTypeCdylib => MetadataKind::None,
771 config::CrateTypeRlib => MetadataKind::Uncompressed,
773 config::CrateTypeDylib |
774 config::CrateTypeProcMacro => MetadataKind::Compressed,
778 if kind == MetadataKind::None {
779 return (metadata_llcx,
781 EncodedMetadata::new(),
782 EncodedMetadataHashes::new());
785 let (metadata, hashes) = tcx.encode_metadata(link_meta, exported_symbols);
786 if kind == MetadataKind::Uncompressed {
787 return (metadata_llcx, metadata_llmod, metadata, hashes);
790 assert!(kind == MetadataKind::Compressed);
791 let mut compressed = tcx.metadata_encoding_version();
792 DeflateEncoder::new(&mut compressed, Compression::Fast)
793 .write_all(&metadata.raw_data).unwrap();
795 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
796 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
797 let name = symbol_export::metadata_symbol_name(tcx);
798 let buf = CString::new(name).unwrap();
799 let llglobal = unsafe {
800 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
803 llvm::LLVMSetInitializer(llglobal, llconst);
804 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
805 let name = CString::new(section_name).unwrap();
806 llvm::LLVMSetSection(llglobal, name.as_ptr());
808 // Also generate a .section directive to force no
809 // flags, at least for ELF outputs, so that the
810 // metadata doesn't get loaded into memory.
811 let directive = format!(".section {}", section_name);
812 let directive = CString::new(directive).unwrap();
813 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
815 return (metadata_llcx, metadata_llmod, metadata, hashes);
818 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
819 // This is required to satisfy `dllimport` references to static data in .rlibs
820 // when using MSVC linker. We do this only for data, as linker can fix up
821 // code references on its own.
822 // See #26591, #27438
823 fn create_imps(sess: &Session,
824 llvm_module: &ModuleLlvm) {
825 // The x86 ABI seems to require that leading underscores are added to symbol
826 // names, so we need an extra underscore on 32-bit. There's also a leading
827 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
828 // underscores added in front).
829 let prefix = if sess.target.target.target_pointer_width == "32" {
835 let exported: Vec<_> = iter_globals(llvm_module.llmod)
837 llvm::LLVMRustGetLinkage(val) ==
838 llvm::Linkage::ExternalLinkage &&
839 llvm::LLVMIsDeclaration(val) == 0
843 let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
844 for val in exported {
845 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
846 let mut imp_name = prefix.as_bytes().to_vec();
847 imp_name.extend(name.to_bytes());
848 let imp_name = CString::new(imp_name).unwrap();
849 let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
851 imp_name.as_ptr() as *const _);
852 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
853 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
860 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
863 impl Iterator for ValueIter {
864 type Item = ValueRef;
866 fn next(&mut self) -> Option<ValueRef> {
869 self.cur = unsafe { (self.step)(old) };
877 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
880 cur: llvm::LLVMGetFirstGlobal(llmod),
881 step: llvm::LLVMGetNextGlobal,
886 /// The context provided lists a set of reachable ids as calculated by
887 /// middle::reachable, but this contains far more ids and symbols than we're
888 /// actually exposing from the object file. This function will filter the set in
889 /// the context to the set of ids which correspond to symbols that are exposed
890 /// from the object file being generated.
892 /// This list is later used by linkers to determine the set of symbols needed to
893 /// be exposed from a dynamic library and it's also encoded into the metadata.
894 pub fn find_exported_symbols(tcx: TyCtxt) -> NodeSet {
895 tcx.reachable_set(LOCAL_CRATE).iter().cloned().filter(|&id| {
896 // Next, we want to ignore some FFI functions that are not exposed from
897 // this crate. Reachable FFI functions can be lumped into two
900 // 1. Those that are included statically via a static library
901 // 2. Those included otherwise (e.g. dynamically or via a framework)
903 // Although our LLVM module is not literally emitting code for the
904 // statically included symbols, it's an export of our library which
905 // needs to be passed on to the linker and encoded in the metadata.
907 // As a result, if this id is an FFI item (foreign item) then we only
908 // let it through if it's included statically.
909 match tcx.hir.get(id) {
910 hir_map::NodeForeignItem(..) => {
911 let def_id = tcx.hir.local_def_id(id);
912 tcx.is_statically_included_foreign_item(def_id)
915 // Only consider nodes that actually have exported symbols.
916 hir_map::NodeItem(&hir::Item {
917 node: hir::ItemStatic(..), .. }) |
918 hir_map::NodeItem(&hir::Item {
919 node: hir::ItemFn(..), .. }) |
920 hir_map::NodeImplItem(&hir::ImplItem {
921 node: hir::ImplItemKind::Method(..), .. }) => {
922 let def_id = tcx.hir.local_def_id(id);
923 let generics = tcx.generics_of(def_id);
924 let attributes = tcx.get_attrs(def_id);
925 (generics.parent_types == 0 && generics.types.is_empty()) &&
926 // Functions marked with #[inline] are only ever translated
927 // with "internal" linkage and are never exported.
928 !attr::requests_inline(&attributes)
936 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
937 incremental_hashes_map: IncrementalHashesMap,
938 output_filenames: &OutputFilenames)
939 -> OngoingCrateTranslation {
940 check_for_rustc_errors_attr(tcx);
942 // Be careful with this krate: obviously it gives access to the
943 // entire contents of the krate. So if you push any subtasks of
944 // `TransCrate`, you need to be careful to register "reads" of the
945 // particular items that will be processed.
946 let krate = tcx.hir.krate();
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);
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 linker_info = LinkerInfo::new(&shared_ccx);
982 let ongoing_translation = write::start_async_translation(
986 tcx.crate_name(LOCAL_CRATE),
989 shared_ccx.tcx().exported_symbols(),
996 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, metadata_module, true);
998 assert_and_save_dep_graph(tcx,
999 incremental_hashes_map,
1000 metadata_incr_hashes,
1003 ongoing_translation.check_for_errors(tcx.sess);
1005 return ongoing_translation;
1008 // Run the translation item collector and partition the collected items into
1010 let (translation_items, codegen_units) =
1011 shared_ccx.tcx().collect_and_partition_translation_items(LOCAL_CRATE);
1013 assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
1015 let linker_info = LinkerInfo::new(&shared_ccx);
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 tcx.exported_symbols(),
1046 // Translate an allocator shim, if any
1048 // If LTO is enabled and we've got some previous LLVM module we translated
1049 // above, then we can just translate directly into that LLVM module. If not,
1050 // however, we need to create a separate module and trans into that. Note
1051 // that the separate translation is critical for the standard library where
1052 // the rlib's object file doesn't have allocator functions but the dylib
1053 // links in an object file that has allocator functions. When we're
1054 // compiling a final LTO artifact, though, there's no need to worry about
1055 // this as we're not working with this dual "rlib/dylib" functionality.
1056 let allocator_module = if tcx.sess.lto() {
1058 } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1061 context::create_context_and_module(tcx.sess, "allocator");
1062 let modules = ModuleLlvm {
1066 time(tcx.sess.time_passes(), "write allocator module", || {
1067 allocator::trans(tcx, &modules, kind)
1070 Some(ModuleTranslation {
1071 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1072 symbol_name_hash: 0, // we always rebuild allocator shims
1073 source: ModuleSource::Translated(modules),
1074 kind: ModuleKind::Allocator,
1081 if let Some(allocator_module) = allocator_module {
1082 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, allocator_module, false);
1085 let codegen_unit_count = codegen_units.len();
1086 ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess,
1088 codegen_unit_count == 0);
1090 let mut all_stats = Stats::default();
1091 let mut module_dispositions = tcx.sess.opts.incremental.as_ref().map(|_| Vec::new());
1093 // We sort the codegen units by size. This way we can schedule work for LLVM
1094 // a bit more efficiently. Note that "size" is defined rather crudely at the
1095 // moment as it is just the number of TransItems in the CGU, not taking into
1096 // account the size of each TransItem.
1097 let codegen_units = {
1098 let mut codegen_units = codegen_units;
1099 codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
1103 let mut total_trans_time = Duration::new(0, 0);
1105 for (cgu_index, cgu) in codegen_units.into_iter().enumerate() {
1106 ongoing_translation.wait_for_signal_to_translate_item();
1107 ongoing_translation.check_for_errors(tcx.sess);
1109 let start_time = Instant::now();
1112 let _timing_guard = time_graph
1114 .map(|time_graph| time_graph.start(write::TRANS_WORKER_TIMELINE,
1115 write::TRANS_WORK_PACKAGE_KIND));
1116 let dep_node = cgu.work_product_dep_node();
1117 let ((stats, module), _) =
1118 tcx.dep_graph.with_task(dep_node,
1119 AssertDepGraphSafe(&shared_ccx),
1120 AssertDepGraphSafe((cgu,
1121 translation_items.clone(),
1122 tcx.exported_symbols())),
1123 module_translation);
1124 all_stats.extend(stats);
1126 if let Some(ref mut module_dispositions) = module_dispositions {
1127 module_dispositions.push(module.disposition());
1133 let time_to_translate = Instant::now().duration_since(start_time);
1135 // We assume that the cost to run LLVM on a CGU is proportional to
1136 // the time we needed for translating it.
1137 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1138 time_to_translate.subsec_nanos() as u64;
1140 total_trans_time += time_to_translate;
1142 let is_last_cgu = (cgu_index + 1) == codegen_unit_count;
1144 ongoing_translation.submit_translated_module_to_llvm(tcx.sess,
1148 ongoing_translation.check_for_errors(tcx.sess);
1151 // Since the main thread is sometimes blocked during trans, we keep track
1152 // -Ztime-passes output manually.
1153 print_time_passes_entry(tcx.sess.time_passes(),
1154 "translate to LLVM IR",
1157 if let Some(module_dispositions) = module_dispositions {
1158 assert_module_sources::assert_module_sources(tcx, &module_dispositions);
1161 fn module_translation<'a, 'tcx>(
1162 scx: AssertDepGraphSafe<&SharedCrateContext<'a, 'tcx>>,
1163 args: AssertDepGraphSafe<(Arc<CodegenUnit<'tcx>>,
1164 Arc<FxHashSet<TransItem<'tcx>>>,
1165 Arc<ExportedSymbols>)>)
1166 -> (Stats, ModuleTranslation)
1168 // FIXME(#40304): We ought to be using the id as a key and some queries, I think.
1169 let AssertDepGraphSafe(scx) = scx;
1170 let AssertDepGraphSafe((cgu, crate_trans_items, exported_symbols)) = args;
1172 let cgu_name = cgu.name().to_string();
1173 let cgu_id = cgu.work_product_id();
1174 let symbol_name_hash = cgu.compute_symbol_name_hash(scx);
1176 // Check whether there is a previous work-product we can
1177 // re-use. Not only must the file exist, and the inputs not
1178 // be dirty, but the hash of the symbols we will generate must
1180 let previous_work_product =
1181 scx.dep_graph().previous_work_product(&cgu_id).and_then(|work_product| {
1182 if work_product.input_hash == symbol_name_hash {
1183 debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1186 if scx.sess().opts.debugging_opts.incremental_info {
1187 eprintln!("incremental: CGU `{}` invalidated because of \
1188 changed partitioning hash.",
1191 debug!("trans_reuse_previous_work_products: \
1192 not reusing {:?} because hash changed to {:?}",
1193 work_product, symbol_name_hash);
1198 if let Some(buf) = previous_work_product {
1199 // Don't need to translate this module.
1200 let module = ModuleTranslation {
1203 source: ModuleSource::Preexisting(buf.clone()),
1204 kind: ModuleKind::Regular,
1206 return (Stats::default(), module);
1209 // Instantiate translation items without filling out definitions yet...
1210 let lcx = LocalCrateContext::new(scx, cgu, crate_trans_items, exported_symbols);
1212 let ccx = CrateContext::new(scx, &lcx);
1213 let trans_items = ccx.codegen_unit()
1214 .items_in_deterministic_order(ccx.tcx());
1215 for &(trans_item, (linkage, visibility)) in &trans_items {
1216 trans_item.predefine(&ccx, linkage, visibility);
1219 // ... and now that we have everything pre-defined, fill out those definitions.
1220 for &(trans_item, _) in &trans_items {
1221 trans_item.define(&ccx);
1224 // If this codegen unit contains the main function, also create the
1226 maybe_create_entry_wrapper(&ccx);
1228 // Run replace-all-uses-with for statics that need it
1229 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1231 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1232 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1233 llvm::LLVMDeleteGlobal(old_g);
1237 // Create the llvm.used variable
1238 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1239 if !ccx.used_statics().borrow().is_empty() {
1240 let name = CString::new("llvm.used").unwrap();
1241 let section = CString::new("llvm.metadata").unwrap();
1242 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1245 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1246 val_ty(array).to_ref(),
1248 llvm::LLVMSetInitializer(g, array);
1249 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1250 llvm::LLVMSetSection(g, section.as_ptr());
1254 // Finalize debuginfo
1255 if ccx.sess().opts.debuginfo != NoDebugInfo {
1256 debuginfo::finalize(&ccx);
1259 let llvm_module = ModuleLlvm {
1264 // In LTO mode we inject the allocator shim into the existing
1266 if ccx.sess().lto() {
1267 if let Some(kind) = ccx.sess().allocator_kind.get() {
1268 time(ccx.sess().time_passes(), "write allocator module", || {
1270 allocator::trans(ccx.tcx(), &llvm_module, kind);
1276 // Adjust exported symbols for MSVC dllimport
1277 if ccx.sess().target.target.options.is_like_msvc &&
1278 ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1279 create_imps(ccx.sess(), &llvm_module);
1285 source: ModuleSource::Translated(llvm_module),
1286 kind: ModuleKind::Regular,
1290 (lcx.into_stats(), module)
1293 symbol_names_test::report_symbol_names(tcx);
1295 if shared_ccx.sess().trans_stats() {
1296 println!("--- trans stats ---");
1297 println!("n_glues_created: {}", all_stats.n_glues_created.get());
1298 println!("n_null_glues: {}", all_stats.n_null_glues.get());
1299 println!("n_real_glues: {}", all_stats.n_real_glues.get());
1301 println!("n_fns: {}", all_stats.n_fns.get());
1302 println!("n_inlines: {}", all_stats.n_inlines.get());
1303 println!("n_closures: {}", all_stats.n_closures.get());
1304 println!("fn stats:");
1305 all_stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1306 insns_b.cmp(&insns_a)
1308 for tuple in all_stats.fn_stats.borrow().iter() {
1310 (ref name, insns) => {
1311 println!("{} insns, {}", insns, *name);
1317 if shared_ccx.sess().count_llvm_insns() {
1318 for (k, v) in all_stats.llvm_insns.borrow().iter() {
1319 println!("{:7} {}", *v, *k);
1323 ongoing_translation.check_for_errors(tcx.sess);
1325 assert_and_save_dep_graph(tcx,
1326 incremental_hashes_map,
1327 metadata_incr_hashes,
1332 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1333 incremental_hashes_map: IncrementalHashesMap,
1334 metadata_incr_hashes: EncodedMetadataHashes,
1335 link_meta: LinkMeta) {
1336 time(tcx.sess.time_passes(),
1338 || rustc_incremental::assert_dep_graph(tcx));
1340 time(tcx.sess.time_passes(),
1341 "serialize dep graph",
1342 || rustc_incremental::save_dep_graph(tcx,
1343 incremental_hashes_map,
1344 &metadata_incr_hashes,
1345 link_meta.crate_hash));
1348 #[inline(never)] // give this a place in the profiler
1349 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1350 where I: Iterator<Item=&'a TransItem<'tcx>>
1352 let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1353 (trans_item, trans_item.symbol_name(tcx))
1356 (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1360 for pair in (&symbols[..]).windows(2) {
1361 let sym1 = &pair[0].1;
1362 let sym2 = &pair[1].1;
1365 let trans_item1 = pair[0].0;
1366 let trans_item2 = pair[1].0;
1368 let span1 = trans_item1.local_span(tcx);
1369 let span2 = trans_item2.local_span(tcx);
1371 // Deterministically select one of the spans for error reporting
1372 let span = match (span1, span2) {
1373 (Some(span1), Some(span2)) => {
1374 Some(if span1.lo().0 > span2.lo().0 {
1380 (Some(span), None) |
1381 (None, Some(span)) => Some(span),
1385 let error_message = format!("symbol `{}` is already defined", sym1);
1387 if let Some(span) = span {
1388 tcx.sess.span_fatal(span, &error_message)
1390 tcx.sess.fatal(&error_message)
1396 fn collect_and_partition_translation_items<'a, 'tcx>(
1397 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1399 ) -> (Arc<FxHashSet<TransItem<'tcx>>>, Vec<Arc<CodegenUnit<'tcx>>>)
1401 assert_eq!(cnum, LOCAL_CRATE);
1402 let time_passes = tcx.sess.time_passes();
1403 let exported_symbols = tcx.exported_symbols();
1405 let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
1407 let mode_string = s.to_lowercase();
1408 let mode_string = mode_string.trim();
1409 if mode_string == "eager" {
1410 TransItemCollectionMode::Eager
1412 if mode_string != "lazy" {
1413 let message = format!("Unknown codegen-item collection mode '{}'. \
1414 Falling back to 'lazy' mode.",
1416 tcx.sess.warn(&message);
1419 TransItemCollectionMode::Lazy
1422 None => TransItemCollectionMode::Lazy
1425 let (items, inlining_map) =
1426 time(time_passes, "translation item collection", || {
1427 collector::collect_crate_translation_items(tcx,
1432 assert_symbols_are_distinct(tcx, items.iter());
1434 let strategy = if tcx.sess.opts.debugging_opts.incremental.is_some() {
1435 PartitioningStrategy::PerModule
1437 PartitioningStrategy::FixedUnitCount(tcx.sess.opts.cg.codegen_units)
1440 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1441 partitioning::partition(tcx,
1442 items.iter().cloned(),
1448 .collect::<Vec<_>>()
1451 assert!(tcx.sess.opts.cg.codegen_units == codegen_units.len() ||
1452 tcx.sess.opts.debugging_opts.incremental.is_some());
1454 let translation_items: FxHashSet<TransItem<'tcx>> = items.iter().cloned().collect();
1456 if tcx.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(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 Linkage::External => "External",
1482 Linkage::AvailableExternally => "Available",
1483 Linkage::LinkOnceAny => "OnceAny",
1484 Linkage::LinkOnceODR => "OnceODR",
1485 Linkage::WeakAny => "WeakAny",
1486 Linkage::WeakODR => "WeakODR",
1487 Linkage::Appending => "Appending",
1488 Linkage::Internal => "Internal",
1489 Linkage::Private => "Private",
1490 Linkage::ExternalWeak => "ExternalWeak",
1491 Linkage::Common => "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 (Arc::new(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);
1555 pub fn provide(providers: &mut Providers) {
1556 providers.collect_and_partition_translation_items =
1557 collect_and_partition_translation_items;
1560 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1562 Linkage::External => llvm::Linkage::ExternalLinkage,
1563 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1564 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1565 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1566 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1567 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1568 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1569 Linkage::Internal => llvm::Linkage::InternalLinkage,
1570 Linkage::Private => llvm::Linkage::PrivateLinkage,
1571 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1572 Linkage::Common => llvm::Linkage::CommonLinkage,
1576 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1578 Visibility::Default => llvm::Visibility::Default,
1579 Visibility::Hidden => llvm::Visibility::Hidden,
1580 Visibility::Protected => llvm::Visibility::Protected,