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::symbol_export;
34 use back::write::{self, OngoingCrateTranslation, create_target_machine};
35 use llvm::{ContextRef, ModuleRef, ValueRef, Vector, get_param};
38 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
39 use rustc::middle::lang_items::StartFnLangItem;
40 use rustc::middle::trans::{Linkage, Visibility, Stats};
41 use rustc::middle::cstore::{EncodedMetadata, EncodedMetadataHashes};
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::ty::maps::Providers;
44 use rustc::dep_graph::{DepNode, DepKind, DepConstructor};
45 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
46 use rustc::util::common::{time, print_time_passes_entry};
47 use rustc::session::config::{self, NoDebugInfo};
48 use rustc::session::Session;
49 use rustc_incremental;
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};
69 use monomorphize::{self, Instance};
70 use partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
71 use symbol_names_test;
73 use trans_item::{TransItem, TransItemExt, DefPathBasedNames};
77 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet, DefIdSet};
81 use std::ffi::{CStr, CString};
84 use std::time::{Instant, Duration};
88 use syntax_pos::symbol::InternedString;
93 use mir::lvalue::Alignment;
95 pub use rustc_trans_utils::{find_exported_symbols, check_for_rustc_errors_attr};
97 pub struct StatRecorder<'a, 'tcx: 'a> {
98 ccx: &'a CrateContext<'a, 'tcx>,
103 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
104 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
105 let istart = ccx.stats().borrow().n_llvm_insns;
114 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
116 if self.ccx.sess().trans_stats() {
117 let mut stats = self.ccx.stats().borrow_mut();
118 let iend = stats.n_llvm_insns;
119 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
121 // Reset LLVM insn count to avoid compound costs.
122 stats.n_llvm_insns = self.istart;
127 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
128 bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
131 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
132 bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
135 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
137 -> llvm::IntPredicate {
139 hir::BiEq => llvm::IntEQ,
140 hir::BiNe => llvm::IntNE,
141 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
142 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
143 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
144 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
146 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
153 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
155 hir::BiEq => llvm::RealOEQ,
156 hir::BiNe => llvm::RealUNE,
157 hir::BiLt => llvm::RealOLT,
158 hir::BiLe => llvm::RealOLE,
159 hir::BiGt => llvm::RealOGT,
160 hir::BiGe => llvm::RealOGE,
162 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
169 pub fn compare_simd_types<'a, 'tcx>(
170 bcx: &Builder<'a, 'tcx>,
177 let signed = match t.sty {
179 let cmp = bin_op_to_fcmp_predicate(op);
180 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
182 ty::TyUint(_) => false,
183 ty::TyInt(_) => true,
184 _ => bug!("compare_simd_types: invalid SIMD type"),
187 let cmp = bin_op_to_icmp_predicate(op, signed);
188 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
189 // to get the correctly sized type. This will compile to a single instruction
190 // once the IR is converted to assembly if the SIMD instruction is supported
191 // by the target architecture.
192 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
195 /// Retrieve the information we are losing (making dynamic) in an unsizing
198 /// The `old_info` argument is a bit funny. It is intended for use
199 /// in an upcast, where the new vtable for an object will be derived
200 /// from the old one.
201 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
204 old_info: Option<ValueRef>)
206 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
207 match (&source.sty, &target.sty) {
208 (&ty::TyArray(_, len), &ty::TySlice(_)) => {
209 C_usize(ccx, len.val.to_const_int().unwrap().to_u64().unwrap())
211 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
212 // For now, upcasts are limited to changes in marker
213 // traits, and hence never actually require an actual
214 // change to the vtable.
215 old_info.expect("unsized_info: missing old info for trait upcast")
217 (_, &ty::TyDynamic(ref data, ..)) => {
218 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
219 Type::vtable_ptr(ccx))
221 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
227 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
228 pub fn unsize_thin_ptr<'a, 'tcx>(
229 bcx: &Builder<'a, 'tcx>,
233 ) -> (ValueRef, ValueRef) {
234 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
235 match (&src_ty.sty, &dst_ty.sty) {
236 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
237 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
238 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
239 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
240 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
241 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
242 assert!(bcx.ccx.shared().type_is_sized(a));
243 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
244 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
246 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
247 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
248 assert!(bcx.ccx.shared().type_is_sized(a));
249 let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
250 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
252 _ => bug!("unsize_thin_ptr: called on bad types"),
256 /// Coerce `src`, which is a reference to a value of type `src_ty`,
257 /// to a value of type `dst_ty` and store the result in `dst`
258 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
259 src: &LvalueRef<'tcx>,
260 dst: &LvalueRef<'tcx>) {
261 let src_ty = src.ty.to_ty(bcx.tcx());
262 let dst_ty = dst.ty.to_ty(bcx.tcx());
263 let coerce_ptr = || {
264 let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
265 // fat-ptr to fat-ptr unsize preserves the vtable
266 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
267 // So we need to pointercast the base to ensure
268 // the types match up.
269 let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
270 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
271 let base = bcx.pointercast(base, llcast_ty);
274 let base = load_ty(bcx, src.llval, src.alignment, src_ty);
275 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
277 store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
279 match (&src_ty.sty, &dst_ty.sty) {
280 (&ty::TyRef(..), &ty::TyRef(..)) |
281 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
282 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
285 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
289 (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
290 assert_eq!(def_a, def_b);
292 let src_fields = def_a.variants[0].fields.iter().map(|f| {
293 monomorphize::field_ty(bcx.tcx(), substs_a, f)
295 let dst_fields = def_b.variants[0].fields.iter().map(|f| {
296 monomorphize::field_ty(bcx.tcx(), substs_b, f)
299 let iter = src_fields.zip(dst_fields).enumerate();
300 for (i, (src_fty, dst_fty)) in iter {
301 if type_is_zero_size(bcx.ccx, dst_fty) {
305 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
306 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
307 if src_fty == dst_fty {
308 memcpy_ty(bcx, dst_f, src_f, src_fty, None);
312 &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
313 &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
318 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
324 pub fn cast_shift_expr_rhs(
325 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
327 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
330 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
334 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
335 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
338 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
344 where F: FnOnce(ValueRef, Type) -> ValueRef,
345 G: FnOnce(ValueRef, Type) -> ValueRef
347 // Shifts may have any size int on the rhs
349 let mut rhs_llty = val_ty(rhs);
350 let mut lhs_llty = val_ty(lhs);
351 if rhs_llty.kind() == Vector {
352 rhs_llty = rhs_llty.element_type()
354 if lhs_llty.kind() == Vector {
355 lhs_llty = lhs_llty.element_type()
357 let rhs_sz = rhs_llty.int_width();
358 let lhs_sz = lhs_llty.int_width();
361 } else if lhs_sz > rhs_sz {
362 // FIXME (#1877: If shifting by negative
363 // values becomes not undefined then this is wrong.
373 /// Returns whether this session's target will use SEH-based unwinding.
375 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
376 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
377 /// 64-bit MinGW) instead of "full SEH".
378 pub fn wants_msvc_seh(sess: &Session) -> bool {
379 sess.target.target.options.is_like_msvc
382 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
383 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
384 b.call(assume_intrinsic, &[val], None);
387 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
388 /// differs from the type used for SSA values. Also handles various special cases where the type
389 /// gives us better information about what we are loading.
390 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
391 alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
393 if type_is_zero_size(ccx, t) {
394 return C_undef(type_of::type_of(ccx, t));
398 let global = llvm::LLVMIsAGlobalVariable(ptr);
399 if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
400 let val = llvm::LLVMGetInitializer(global);
403 return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
411 b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
413 } else if t.is_char() {
414 // a char is a Unicode codepoint, and so takes values from 0
415 // to 0x10FFFF inclusive only.
416 b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
417 } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
418 && !common::type_is_fat_ptr(ccx, t)
420 b.load_nonnull(ptr, alignment.to_align())
422 b.load(ptr, alignment.to_align())
426 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
427 /// differs from the type used for SSA values.
428 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
429 dst_align: Alignment, t: Ty<'tcx>) {
430 debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
432 if common::type_is_fat_ptr(cx.ccx, t) {
433 let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
434 let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
435 store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
437 cx.store(from_immediate(cx, v), dst, dst_align.to_align());
441 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
445 dst_align: Alignment,
447 // FIXME: emit metadata
448 cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
449 cx.store(extra, get_meta(cx, dst), dst_align.to_align());
452 pub fn load_fat_ptr<'a, 'tcx>(
453 b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
454 ) -> (ValueRef, ValueRef) {
455 let ptr = get_dataptr(b, src);
456 let ptr = if t.is_region_ptr() || t.is_box() {
457 b.load_nonnull(ptr, alignment.to_align())
459 b.load(ptr, alignment.to_align())
462 let meta = get_meta(b, src);
463 let meta_ty = val_ty(meta);
464 // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
466 let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
467 b.load_nonnull(meta, None)
475 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
476 if val_ty(val) == Type::i1(bcx.ccx) {
477 bcx.zext(val, Type::i8(bcx.ccx))
483 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
485 bcx.trunc(val, Type::i1(bcx.ccx))
491 pub enum Lifetime { Start, End }
494 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
495 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
496 // and the intrinsic for `lt` and passes them to `emit`, which is in
497 // charge of generating code to call the passed intrinsic on whatever
498 // block of generated code is targeted for the intrinsic.
500 // If LLVM lifetime intrinsic support is disabled (i.e. optimizations
501 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
502 pub fn call(self, b: &Builder, ptr: ValueRef) {
503 if b.ccx.sess().opts.optimize == config::OptLevel::No {
507 let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
512 let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
513 Lifetime::Start => "llvm.lifetime.start",
514 Lifetime::End => "llvm.lifetime.end"
517 let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
518 b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
522 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
528 let ptr_width = &ccx.sess().target.target.target_pointer_width;
529 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
530 let memcpy = ccx.get_intrinsic(&key);
531 let src_ptr = b.pointercast(src, Type::i8p(ccx));
532 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
533 let size = b.intcast(n_bytes, ccx.isize_ty(), false);
534 let align = C_i32(ccx, align as i32);
535 let volatile = C_bool(ccx, false);
536 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
539 pub fn memcpy_ty<'a, 'tcx>(
540 bcx: &Builder<'a, 'tcx>,
548 let size = ccx.size_of(t);
553 let align = align.unwrap_or_else(|| ccx.align_of(t));
554 call_memcpy(bcx, dst, src, C_usize(ccx, size), align);
557 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
562 volatile: bool) -> ValueRef {
563 let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
564 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
565 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
566 let volatile = C_bool(b.ccx, volatile);
567 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
570 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
571 let _s = if ccx.sess().trans_stats() {
572 let mut instance_name = String::new();
573 DefPathBasedNames::new(ccx.tcx(), true, true)
574 .push_def_path(instance.def_id(), &mut instance_name);
575 Some(StatRecorder::new(ccx, instance_name))
580 // this is an info! to allow collecting monomorphization statistics
581 // and to allow finding the last function before LLVM aborts from
583 info!("trans_instance({})", instance);
585 let fn_ty = common::instance_ty(ccx.tcx(), &instance);
586 let sig = common::ty_fn_sig(ccx, fn_ty);
587 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
589 let lldecl = match ccx.instances().borrow().get(&instance) {
591 None => bug!("Instance `{:?}` not already declared", instance)
594 ccx.stats().borrow_mut().n_closures += 1;
596 // The `uwtable` attribute according to LLVM is:
598 // This attribute indicates that the ABI being targeted requires that an
599 // unwind table entry be produced for this function even if we can show
600 // that no exceptions passes by it. This is normally the case for the
601 // ELF x86-64 abi, but it can be disabled for some compilation units.
603 // Typically when we're compiling with `-C panic=abort` (which implies this
604 // `no_landing_pads` check) we don't need `uwtable` because we can't
605 // generate any exceptions! On Windows, however, exceptions include other
606 // events such as illegal instructions, segfaults, etc. This means that on
607 // Windows we end up still needing the `uwtable` attribute even if the `-C
608 // panic=abort` flag is passed.
610 // You can also find more info on why Windows is whitelisted here in:
611 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
612 if !ccx.sess().no_landing_pads() ||
613 ccx.sess().target.target.options.is_like_windows {
614 attributes::emit_uwtable(lldecl, true);
617 let mir = ccx.tcx().instance_mir(instance.def);
618 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
621 pub fn linkage_by_name(name: &str) -> Option<Linkage> {
622 use rustc::middle::trans::Linkage::*;
624 // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
625 // applicable to variable declarations and may not really make sense for
626 // Rust code in the first place but whitelist them anyway and trust that
627 // the user knows what s/he's doing. Who knows, unanticipated use cases
628 // may pop up in the future.
630 // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
631 // and don't have to be, LLVM treats them as no-ops.
633 "appending" => Some(Appending),
634 "available_externally" => Some(AvailableExternally),
635 "common" => Some(Common),
636 "extern_weak" => Some(ExternalWeak),
637 "external" => Some(External),
638 "internal" => Some(Internal),
639 "linkonce" => Some(LinkOnceAny),
640 "linkonce_odr" => Some(LinkOnceODR),
641 "private" => Some(Private),
642 "weak" => Some(WeakAny),
643 "weak_odr" => Some(WeakODR),
648 pub fn set_link_section(ccx: &CrateContext,
650 attrs: &[ast::Attribute]) {
651 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
652 if contains_null(§.as_str()) {
653 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
656 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
657 llvm::LLVMSetSection(llval, buf.as_ptr());
662 /// Create the `main` function which will initialize the rust runtime and call
663 /// users main function.
664 fn maybe_create_entry_wrapper(ccx: &CrateContext) {
665 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
666 Some((id, span)) => {
667 (ccx.tcx().hir.local_def_id(id), span)
672 let instance = Instance::mono(ccx.tcx(), main_def_id);
674 if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
675 // We want to create the wrapper in the same codegen unit as Rust's main
680 let main_llfn = callee::get_fn(ccx, instance);
682 let et = ccx.sess().entry_type.get().unwrap();
684 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
685 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
686 config::EntryNone => {} // Do nothing.
689 fn create_entry_fn(ccx: &CrateContext,
692 use_start_lang_item: bool) {
693 // Signature of native main(), corresponding to C's `int main(int, char **)`
694 let llfty = Type::func(&[Type::c_int(ccx), Type::i8p(ccx).ptr_to()], &Type::c_int(ccx));
696 if declare::get_defined_value(ccx, "main").is_some() {
697 // FIXME: We should be smart and show a better diagnostic here.
698 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
699 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
701 ccx.sess().abort_if_errors();
704 let llfn = declare::declare_cfn(ccx, "main", llfty);
706 // `main` should respect same config for frame pointer elimination as rest of code
707 attributes::set_frame_pointer_elimination(ccx, llfn);
709 let bld = Builder::new_block(ccx, llfn, "top");
711 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
713 // Params from native main() used as args for rust start function
714 let param_argc = get_param(llfn, 0);
715 let param_argv = get_param(llfn, 1);
716 let arg_argc = bld.intcast(param_argc, ccx.isize_ty(), true);
717 let arg_argv = param_argv;
719 let (start_fn, args) = if use_start_lang_item {
720 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
721 let start_instance = Instance::mono(ccx.tcx(), start_def_id);
722 let start_fn = callee::get_fn(ccx, start_instance);
723 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()),
726 debug!("using user-defined start fn");
727 (rust_main, vec![arg_argc, arg_argv])
730 let result = bld.call(start_fn, &args, None);
732 // Return rust start function's result from native main()
733 bld.ret(bld.intcast(result, Type::c_int(ccx), true));
737 fn contains_null(s: &str) -> bool {
738 s.bytes().any(|b| b == 0)
741 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
743 link_meta: &LinkMeta,
744 exported_symbols: &NodeSet)
745 -> (ContextRef, ModuleRef,
746 EncodedMetadata, EncodedMetadataHashes) {
748 use flate2::Compression;
749 use flate2::write::DeflateEncoder;
751 let (metadata_llcx, metadata_llmod) = unsafe {
752 context::create_context_and_module(tcx.sess, llmod_id)
755 #[derive(PartialEq, Eq, PartialOrd, Ord)]
762 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
764 config::CrateTypeExecutable |
765 config::CrateTypeStaticlib |
766 config::CrateTypeCdylib => MetadataKind::None,
768 config::CrateTypeRlib => MetadataKind::Uncompressed,
770 config::CrateTypeDylib |
771 config::CrateTypeProcMacro => MetadataKind::Compressed,
775 if kind == MetadataKind::None {
776 return (metadata_llcx,
778 EncodedMetadata::new(),
779 EncodedMetadataHashes::new());
782 let (metadata, hashes) = tcx.encode_metadata(link_meta, exported_symbols);
783 if kind == MetadataKind::Uncompressed {
784 return (metadata_llcx, metadata_llmod, metadata, hashes);
787 assert!(kind == MetadataKind::Compressed);
788 let mut compressed = tcx.metadata_encoding_version();
789 DeflateEncoder::new(&mut compressed, Compression::Fast)
790 .write_all(&metadata.raw_data).unwrap();
792 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
793 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
794 let name = symbol_export::metadata_symbol_name(tcx);
795 let buf = CString::new(name).unwrap();
796 let llglobal = unsafe {
797 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
800 llvm::LLVMSetInitializer(llglobal, llconst);
801 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
802 let name = CString::new(section_name).unwrap();
803 llvm::LLVMSetSection(llglobal, name.as_ptr());
805 // Also generate a .section directive to force no
806 // flags, at least for ELF outputs, so that the
807 // metadata doesn't get loaded into memory.
808 let directive = format!(".section {}", section_name);
809 let directive = CString::new(directive).unwrap();
810 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
812 return (metadata_llcx, metadata_llmod, metadata, hashes);
815 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
816 // This is required to satisfy `dllimport` references to static data in .rlibs
817 // when using MSVC linker. We do this only for data, as linker can fix up
818 // code references on its own.
819 // See #26591, #27438
820 fn create_imps(sess: &Session,
821 llvm_module: &ModuleLlvm) {
822 // The x86 ABI seems to require that leading underscores are added to symbol
823 // names, so we need an extra underscore on 32-bit. There's also a leading
824 // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
825 // underscores added in front).
826 let prefix = if sess.target.target.target_pointer_width == "32" {
832 let exported: Vec<_> = iter_globals(llvm_module.llmod)
834 llvm::LLVMRustGetLinkage(val) ==
835 llvm::Linkage::ExternalLinkage &&
836 llvm::LLVMIsDeclaration(val) == 0
840 let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
841 for val in exported {
842 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
843 let mut imp_name = prefix.as_bytes().to_vec();
844 imp_name.extend(name.to_bytes());
845 let imp_name = CString::new(imp_name).unwrap();
846 let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
848 imp_name.as_ptr() as *const _);
849 llvm::LLVMSetInitializer(imp, consts::ptrcast(val, i8p_ty));
850 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
857 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
860 impl Iterator for ValueIter {
861 type Item = ValueRef;
863 fn next(&mut self) -> Option<ValueRef> {
866 self.cur = unsafe { (self.step)(old) };
874 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
877 cur: llvm::LLVMGetFirstGlobal(llmod),
878 step: llvm::LLVMGetNextGlobal,
883 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
884 rx: mpsc::Receiver<Box<Any + Send>>)
885 -> OngoingCrateTranslation {
887 check_for_rustc_errors_attr(tcx);
890 let crate_hash = tcx.dep_graph
891 .fingerprint_of(&DepNode::new_no_params(DepKind::Krate));
892 let link_meta = link::build_link_meta(crate_hash);
893 let exported_symbol_node_ids = find_exported_symbols(tcx);
895 let shared_ccx = SharedCrateContext::new(tcx);
896 // Translate the metadata.
897 let llmod_id = "metadata";
898 let (metadata_llcx, metadata_llmod, metadata, metadata_incr_hashes) =
899 time(tcx.sess.time_passes(), "write metadata", || {
900 write_metadata(tcx, llmod_id, &link_meta, &exported_symbol_node_ids)
903 let metadata_module = ModuleTranslation {
904 name: link::METADATA_MODULE_NAME.to_string(),
905 llmod_id: llmod_id.to_string(),
906 source: ModuleSource::Translated(ModuleLlvm {
908 llmod: metadata_llmod,
909 tm: create_target_machine(tcx.sess),
911 kind: ModuleKind::Metadata,
914 let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
915 Some(time_graph::TimeGraph::new())
920 // Skip crate items and just output metadata in -Z no-trans mode.
921 if tcx.sess.opts.debugging_opts.no_trans ||
922 !tcx.sess.opts.output_types.should_trans() {
923 let ongoing_translation = write::start_async_translation(
930 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
931 ongoing_translation.translation_finished(tcx);
933 assert_and_save_dep_graph(tcx,
934 metadata_incr_hashes,
937 ongoing_translation.check_for_errors(tcx.sess);
939 return ongoing_translation;
942 // Run the translation item collector and partition the collected items into
945 shared_ccx.tcx().collect_and_partition_translation_items(LOCAL_CRATE).1;
946 let codegen_units = (*codegen_units).clone();
948 // Force all codegen_unit queries so they are already either red or green
949 // when compile_codegen_unit accesses them. We are not able to re-execute
950 // the codegen_unit query from just the DepNode, so an unknown color would
951 // lead to having to re-execute compile_codegen_unit, possibly
953 if tcx.dep_graph.is_fully_enabled() {
954 for cgu in &codegen_units {
955 tcx.codegen_unit(cgu.name().clone());
959 assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
961 let ongoing_translation = write::start_async_translation(
968 // Translate an allocator shim, if any
969 let allocator_module = if let Some(kind) = tcx.sess.allocator_kind.get() {
971 let llmod_id = "allocator";
973 context::create_context_and_module(tcx.sess, llmod_id);
974 let modules = ModuleLlvm {
977 tm: create_target_machine(tcx.sess),
979 time(tcx.sess.time_passes(), "write allocator module", || {
980 allocator::trans(tcx, &modules, kind)
983 Some(ModuleTranslation {
984 name: link::ALLOCATOR_MODULE_NAME.to_string(),
985 llmod_id: llmod_id.to_string(),
986 source: ModuleSource::Translated(modules),
987 kind: ModuleKind::Allocator,
994 if let Some(allocator_module) = allocator_module {
995 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, allocator_module);
998 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
1000 // We sort the codegen units by size. This way we can schedule work for LLVM
1001 // a bit more efficiently. Note that "size" is defined rather crudely at the
1002 // moment as it is just the number of TransItems in the CGU, not taking into
1003 // account the size of each TransItem.
1004 let codegen_units = {
1005 let mut codegen_units = codegen_units;
1006 codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
1010 let mut total_trans_time = Duration::new(0, 0);
1011 let mut all_stats = Stats::default();
1013 for cgu in codegen_units.into_iter() {
1014 ongoing_translation.wait_for_signal_to_translate_item();
1015 ongoing_translation.check_for_errors(tcx.sess);
1017 // First, if incremental compilation is enabled, we try to re-use the
1018 // codegen unit from the cache.
1019 if tcx.dep_graph.is_fully_enabled() {
1020 let cgu_id = cgu.work_product_id();
1022 // Check whether there is a previous work-product we can
1023 // re-use. Not only must the file exist, and the inputs not
1024 // be dirty, but the hash of the symbols we will generate must
1026 if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
1027 let dep_node = &DepNode::new(tcx,
1028 DepConstructor::CompileCodegenUnit(cgu.name().clone()));
1030 // We try to mark the DepNode::CompileCodegenUnit green. If we
1031 // succeed it means that none of the dependencies has changed
1032 // and we can safely re-use.
1033 if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
1034 // Append ".rs" to LLVM module identifier.
1036 // LLVM code generator emits a ".file filename" directive
1037 // for ELF backends. Value of the "filename" is set as the
1038 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
1039 // crashes if the module identifier is same as other symbols
1040 // such as a function name in the module.
1041 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
1042 let llmod_id = format!("{}.rs", cgu.name());
1044 let module = ModuleTranslation {
1045 name: cgu.name().to_string(),
1046 source: ModuleSource::Preexisting(buf),
1047 kind: ModuleKind::Regular,
1050 tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
1051 write::submit_translated_module_to_llvm(tcx, module, 0);
1052 // Continue to next cgu, this one is done.
1056 // This can happen if files were deleted from the cache
1057 // directory for some reason. We just re-compile then.
1061 let _timing_guard = time_graph.as_ref().map(|time_graph| {
1062 time_graph.start(write::TRANS_WORKER_TIMELINE,
1063 write::TRANS_WORK_PACKAGE_KIND,
1064 &format!("codegen {}", cgu.name()))
1066 let start_time = Instant::now();
1067 all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
1068 total_trans_time += start_time.elapsed();
1069 ongoing_translation.check_for_errors(tcx.sess);
1072 ongoing_translation.translation_finished(tcx);
1074 // Since the main thread is sometimes blocked during trans, we keep track
1075 // -Ztime-passes output manually.
1076 print_time_passes_entry(tcx.sess.time_passes(),
1077 "translate to LLVM IR",
1080 if tcx.sess.opts.incremental.is_some() {
1081 assert_module_sources::assert_module_sources(tcx);
1084 symbol_names_test::report_symbol_names(tcx);
1086 if shared_ccx.sess().trans_stats() {
1087 println!("--- trans stats ---");
1088 println!("n_glues_created: {}", all_stats.n_glues_created);
1089 println!("n_null_glues: {}", all_stats.n_null_glues);
1090 println!("n_real_glues: {}", all_stats.n_real_glues);
1092 println!("n_fns: {}", all_stats.n_fns);
1093 println!("n_inlines: {}", all_stats.n_inlines);
1094 println!("n_closures: {}", all_stats.n_closures);
1095 println!("fn stats:");
1096 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
1097 for &(ref name, insns) in all_stats.fn_stats.iter() {
1098 println!("{} insns, {}", insns, *name);
1102 if shared_ccx.sess().count_llvm_insns() {
1103 for (k, v) in all_stats.llvm_insns.iter() {
1104 println!("{:7} {}", *v, *k);
1108 ongoing_translation.check_for_errors(tcx.sess);
1110 assert_and_save_dep_graph(tcx,
1111 metadata_incr_hashes,
1116 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1117 metadata_incr_hashes: EncodedMetadataHashes,
1118 link_meta: LinkMeta) {
1119 time(tcx.sess.time_passes(),
1121 || rustc_incremental::assert_dep_graph(tcx));
1123 time(tcx.sess.time_passes(),
1124 "serialize dep graph",
1125 || rustc_incremental::save_dep_graph(tcx,
1126 &metadata_incr_hashes,
1127 link_meta.crate_hash));
1130 #[inline(never)] // give this a place in the profiler
1131 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1132 where I: Iterator<Item=&'a TransItem<'tcx>>
1134 let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1135 (trans_item, trans_item.symbol_name(tcx))
1138 (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1142 for pair in (&symbols[..]).windows(2) {
1143 let sym1 = &pair[0].1;
1144 let sym2 = &pair[1].1;
1147 let trans_item1 = pair[0].0;
1148 let trans_item2 = pair[1].0;
1150 let span1 = trans_item1.local_span(tcx);
1151 let span2 = trans_item2.local_span(tcx);
1153 // Deterministically select one of the spans for error reporting
1154 let span = match (span1, span2) {
1155 (Some(span1), Some(span2)) => {
1156 Some(if span1.lo().0 > span2.lo().0 {
1162 (Some(span), None) |
1163 (None, Some(span)) => Some(span),
1167 let error_message = format!("symbol `{}` is already defined", sym1);
1169 if let Some(span) = span {
1170 tcx.sess.span_fatal(span, &error_message)
1172 tcx.sess.fatal(&error_message)
1178 fn collect_and_partition_translation_items<'a, 'tcx>(
1179 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1181 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
1183 assert_eq!(cnum, LOCAL_CRATE);
1184 let time_passes = tcx.sess.time_passes();
1186 let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
1188 let mode_string = s.to_lowercase();
1189 let mode_string = mode_string.trim();
1190 if mode_string == "eager" {
1191 TransItemCollectionMode::Eager
1193 if mode_string != "lazy" {
1194 let message = format!("Unknown codegen-item collection mode '{}'. \
1195 Falling back to 'lazy' mode.",
1197 tcx.sess.warn(&message);
1200 TransItemCollectionMode::Lazy
1203 None => TransItemCollectionMode::Lazy
1206 let (items, inlining_map) =
1207 time(time_passes, "translation item collection", || {
1208 collector::collect_crate_translation_items(tcx, collection_mode)
1211 assert_symbols_are_distinct(tcx, items.iter());
1213 let strategy = if tcx.sess.opts.debugging_opts.incremental.is_some() {
1214 PartitioningStrategy::PerModule
1216 PartitioningStrategy::FixedUnitCount(tcx.sess.opts.codegen_units)
1219 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1220 partitioning::partition(tcx,
1221 items.iter().cloned(),
1226 .collect::<Vec<_>>()
1229 assert!(tcx.sess.opts.codegen_units == codegen_units.len() ||
1230 tcx.sess.opts.debugging_opts.incremental.is_some());
1232 let translation_items: DefIdSet = items.iter().filter_map(|trans_item| {
1234 TransItem::Fn(ref instance) => Some(instance.def_id()),
1239 if tcx.sess.opts.debugging_opts.print_trans_items.is_some() {
1240 let mut item_to_cgus = FxHashMap();
1242 for cgu in &codegen_units {
1243 for (&trans_item, &linkage) in cgu.items() {
1244 item_to_cgus.entry(trans_item)
1245 .or_insert(Vec::new())
1246 .push((cgu.name().clone(), linkage));
1250 let mut item_keys: Vec<_> = items
1253 let mut output = i.to_string(tcx);
1254 output.push_str(" @@");
1255 let mut empty = Vec::new();
1256 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1257 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1259 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1260 output.push_str(" ");
1261 output.push_str(&cgu_name);
1263 let linkage_abbrev = match linkage {
1264 Linkage::External => "External",
1265 Linkage::AvailableExternally => "Available",
1266 Linkage::LinkOnceAny => "OnceAny",
1267 Linkage::LinkOnceODR => "OnceODR",
1268 Linkage::WeakAny => "WeakAny",
1269 Linkage::WeakODR => "WeakODR",
1270 Linkage::Appending => "Appending",
1271 Linkage::Internal => "Internal",
1272 Linkage::Private => "Private",
1273 Linkage::ExternalWeak => "ExternalWeak",
1274 Linkage::Common => "Common",
1277 output.push_str("[");
1278 output.push_str(linkage_abbrev);
1279 output.push_str("]");
1287 for item in item_keys {
1288 println!("TRANS_ITEM {}", item);
1292 (Arc::new(translation_items), Arc::new(codegen_units))
1296 pub fn new(tcx: TyCtxt) -> CrateInfo {
1297 let mut info = CrateInfo {
1298 panic_runtime: None,
1299 compiler_builtins: None,
1300 profiler_runtime: None,
1301 sanitizer_runtime: None,
1302 is_no_builtins: FxHashSet(),
1303 native_libraries: FxHashMap(),
1304 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1305 link_args: tcx.link_args(LOCAL_CRATE),
1306 crate_name: FxHashMap(),
1307 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1308 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1309 used_crate_source: FxHashMap(),
1312 for &cnum in tcx.crates().iter() {
1313 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1314 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1315 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1316 if tcx.is_panic_runtime(cnum) {
1317 info.panic_runtime = Some(cnum);
1319 if tcx.is_compiler_builtins(cnum) {
1320 info.compiler_builtins = Some(cnum);
1322 if tcx.is_profiler_runtime(cnum) {
1323 info.profiler_runtime = Some(cnum);
1325 if tcx.is_sanitizer_runtime(cnum) {
1326 info.sanitizer_runtime = Some(cnum);
1328 if tcx.is_no_builtins(cnum) {
1329 info.is_no_builtins.insert(cnum);
1338 fn is_translated_function(tcx: TyCtxt, id: DefId) -> bool {
1339 let (all_trans_items, _) =
1340 tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1341 all_trans_items.contains(&id)
1344 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1345 cgu: InternedString) -> Stats {
1346 let cgu = tcx.codegen_unit(cgu);
1348 let start_time = Instant::now();
1349 let (stats, module) = module_translation(tcx, cgu);
1350 let time_to_translate = start_time.elapsed();
1352 // We assume that the cost to run LLVM on a CGU is proportional to
1353 // the time we needed for translating it.
1354 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1355 time_to_translate.subsec_nanos() as u64;
1357 write::submit_translated_module_to_llvm(tcx,
1362 fn module_translation<'a, 'tcx>(
1363 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1364 cgu: Arc<CodegenUnit<'tcx>>)
1365 -> (Stats, ModuleTranslation)
1367 let cgu_name = cgu.name().to_string();
1369 // Append ".rs" to LLVM module identifier.
1371 // LLVM code generator emits a ".file filename" directive
1372 // for ELF backends. Value of the "filename" is set as the
1373 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
1374 // crashes if the module identifier is same as other symbols
1375 // such as a function name in the module.
1376 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
1377 let llmod_id = format!("{}.rs", cgu.name());
1379 // Instantiate translation items without filling out definitions yet...
1380 let scx = SharedCrateContext::new(tcx);
1381 let lcx = LocalCrateContext::new(&scx, cgu, &llmod_id);
1383 let ccx = CrateContext::new(&scx, &lcx);
1384 let trans_items = ccx.codegen_unit()
1385 .items_in_deterministic_order(ccx.tcx());
1386 for &(trans_item, (linkage, visibility)) in &trans_items {
1387 trans_item.predefine(&ccx, linkage, visibility);
1390 // ... and now that we have everything pre-defined, fill out those definitions.
1391 for &(trans_item, _) in &trans_items {
1392 trans_item.define(&ccx);
1395 // If this codegen unit contains the main function, also create the
1397 maybe_create_entry_wrapper(&ccx);
1399 // Run replace-all-uses-with for statics that need it
1400 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1402 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1403 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1404 llvm::LLVMDeleteGlobal(old_g);
1408 // Create the llvm.used variable
1409 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1410 if !ccx.used_statics().borrow().is_empty() {
1411 let name = CString::new("llvm.used").unwrap();
1412 let section = CString::new("llvm.metadata").unwrap();
1413 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1416 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1417 val_ty(array).to_ref(),
1419 llvm::LLVMSetInitializer(g, array);
1420 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1421 llvm::LLVMSetSection(g, section.as_ptr());
1425 // Finalize debuginfo
1426 if ccx.sess().opts.debuginfo != NoDebugInfo {
1427 debuginfo::finalize(&ccx);
1430 let llvm_module = ModuleLlvm {
1433 tm: create_target_machine(ccx.sess()),
1436 // Adjust exported symbols for MSVC dllimport
1437 if ccx.sess().target.target.options.is_like_msvc &&
1438 ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1439 create_imps(ccx.sess(), &llvm_module);
1444 source: ModuleSource::Translated(llvm_module),
1445 kind: ModuleKind::Regular,
1450 (lcx.into_stats(), module)
1454 pub fn provide_local(providers: &mut Providers) {
1455 providers.collect_and_partition_translation_items =
1456 collect_and_partition_translation_items;
1458 providers.is_translated_function = is_translated_function;
1460 providers.codegen_unit = |tcx, name| {
1461 let (_, all) = tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1463 .find(|cgu| *cgu.name() == name)
1465 .expect(&format!("failed to find cgu with name {:?}", name))
1467 providers.compile_codegen_unit = compile_codegen_unit;
1470 pub fn provide_extern(providers: &mut Providers) {
1471 providers.is_translated_function = is_translated_function;
1474 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1476 Linkage::External => llvm::Linkage::ExternalLinkage,
1477 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1478 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1479 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1480 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1481 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1482 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1483 Linkage::Internal => llvm::Linkage::InternalLinkage,
1484 Linkage::Private => llvm::Linkage::PrivateLinkage,
1485 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1486 Linkage::Common => llvm::Linkage::CommonLinkage,
1490 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1492 Visibility::Default => llvm::Visibility::Default,
1493 Visibility::Hidden => llvm::Visibility::Hidden,
1494 Visibility::Protected => llvm::Visibility::Protected,
1498 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1499 // the HashStable trait. Normally DepGraph::with_task() calls are
1500 // hidden behind queries, but CGU creation is a special case in two
1501 // ways: (1) it's not a query and (2) CGU are output nodes, so their
1502 // Fingerprints are not actually needed. It remains to be clarified
1503 // how exactly this case will be handled in the red/green system but
1504 // for now we content ourselves with providing a no-op HashStable
1505 // implementation for CGUs.
1506 mod temp_stable_hash_impls {
1507 use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1509 use ModuleTranslation;
1511 impl<HCX> HashStable<HCX> for ModuleTranslation {
1512 fn hash_stable<W: StableHasherResult>(&self,
1514 _: &mut StableHasher<W>) {