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;
33 use back::write::{self, OngoingCrateTranslation, create_target_machine};
34 use llvm::{ContextRef, ModuleRef, ValueRef, Vector, get_param};
37 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
38 use rustc::middle::lang_items::StartFnLangItem;
39 use rustc::mir::mono::{Linkage, Visibility, Stats};
40 use rustc::middle::cstore::{EncodedMetadata};
41 use rustc::ty::{self, Ty, TyCtxt};
42 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf};
43 use rustc::ty::maps::Providers;
44 use rustc::dep_graph::{DepNode, DepConstructor};
45 use rustc::ty::subst::Kind;
46 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
47 use rustc::middle::exported_symbols;
48 use rustc::util::common::{time, print_time_passes_entry};
49 use rustc::session::config::{self, NoDebugInfo};
50 use rustc::session::Session;
51 use rustc_incremental;
53 use mir::place::PlaceRef;
57 use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
58 use rustc_mir::monomorphize::collector::{self, MonoItemCollectionMode};
59 use common::{self, C_struct_in_context, C_array, val_ty};
61 use context::{self, CodegenCx};
66 use monomorphize::Instance;
67 use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
68 use rustc_trans_utils::symbol_names_test;
70 use trans_item::{MonoItem, BaseMonoItemExt, MonoItemExt, DefPathBasedNames};
72 use type_of::LayoutLlvmExt;
73 use rustc::util::nodemap::{FxHashMap, FxHashSet, DefIdSet};
75 use rustc_data_structures::sync::Lrc;
78 use std::collections::BTreeMap;
79 use std::ffi::CString;
82 use std::time::{Instant, Duration};
83 use std::{i32, usize};
87 use syntax_pos::symbol::InternedString;
92 use mir::operand::OperandValue;
94 pub use rustc_trans_utils::check_for_rustc_errors_attr;
96 pub struct StatRecorder<'a, 'tcx: 'a> {
97 cx: &'a CodegenCx<'a, 'tcx>,
102 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
103 pub fn new(cx: &'a CodegenCx<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
104 let istart = cx.stats.borrow().n_llvm_insns;
113 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
115 if self.cx.sess().trans_stats() {
116 let mut stats = self.cx.stats.borrow_mut();
117 let iend = stats.n_llvm_insns;
118 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
120 // Reset LLVM insn count to avoid compound costs.
121 stats.n_llvm_insns = self.istart;
126 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
128 -> llvm::IntPredicate {
130 hir::BiEq => llvm::IntEQ,
131 hir::BiNe => llvm::IntNE,
132 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
133 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
134 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
135 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
137 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
144 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
146 hir::BiEq => llvm::RealOEQ,
147 hir::BiNe => llvm::RealUNE,
148 hir::BiLt => llvm::RealOLT,
149 hir::BiLe => llvm::RealOLE,
150 hir::BiGt => llvm::RealOGT,
151 hir::BiGe => llvm::RealOGE,
153 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
160 pub fn compare_simd_types<'a, 'tcx>(
161 bx: &Builder<'a, 'tcx>,
168 let signed = match t.sty {
170 let cmp = bin_op_to_fcmp_predicate(op);
171 return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
173 ty::TyUint(_) => false,
174 ty::TyInt(_) => true,
175 _ => bug!("compare_simd_types: invalid SIMD type"),
178 let cmp = bin_op_to_icmp_predicate(op, signed);
179 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
180 // to get the correctly sized type. This will compile to a single instruction
181 // once the IR is converted to assembly if the SIMD instruction is supported
182 // by the target architecture.
183 bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
186 /// Retrieve the information we are losing (making dynamic) in an unsizing
189 /// The `old_info` argument is a bit funny. It is intended for use
190 /// in an upcast, where the new vtable for an object will be derived
191 /// from the old one.
192 pub fn unsized_info<'cx, 'tcx>(cx: &CodegenCx<'cx, 'tcx>,
195 old_info: Option<ValueRef>)
197 let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
198 match (&source.sty, &target.sty) {
199 (&ty::TyArray(_, len), &ty::TySlice(_)) => {
200 C_usize(cx, len.val.unwrap_u64())
202 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
203 // For now, upcasts are limited to changes in marker
204 // traits, and hence never actually require an actual
205 // change to the vtable.
206 old_info.expect("unsized_info: missing old info for trait upcast")
208 (_, &ty::TyDynamic(ref data, ..)) => {
209 let vtable_ptr = cx.layout_of(cx.tcx.mk_mut_ptr(target))
210 .field(cx, abi::FAT_PTR_EXTRA);
211 consts::ptrcast(meth::get_vtable(cx, source, data.principal()),
212 vtable_ptr.llvm_type(cx))
214 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
220 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
221 pub fn unsize_thin_ptr<'a, 'tcx>(
222 bx: &Builder<'a, 'tcx>,
226 ) -> (ValueRef, ValueRef) {
227 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
228 match (&src_ty.sty, &dst_ty.sty) {
229 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
230 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
231 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
232 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
233 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
234 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
235 assert!(bx.cx.type_is_sized(a));
236 let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
237 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
239 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
240 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
241 assert!(bx.cx.type_is_sized(a));
242 let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
243 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
245 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
246 assert_eq!(def_a, def_b);
248 let src_layout = bx.cx.layout_of(src_ty);
249 let dst_layout = bx.cx.layout_of(dst_ty);
250 let mut result = None;
251 for i in 0..src_layout.fields.count() {
252 let src_f = src_layout.field(bx.cx, i);
253 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
254 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
258 assert_eq!(src_layout.size, src_f.size);
260 let dst_f = dst_layout.field(bx.cx, i);
261 assert_ne!(src_f.ty, dst_f.ty);
262 assert_eq!(result, None);
263 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
265 let (lldata, llextra) = result.unwrap();
266 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
267 (bx.bitcast(lldata, dst_layout.scalar_pair_element_llvm_type(bx.cx, 0)),
268 bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1)))
270 _ => bug!("unsize_thin_ptr: called on bad types"),
274 /// Coerce `src`, which is a reference to a value of type `src_ty`,
275 /// to a value of type `dst_ty` and store the result in `dst`
276 pub fn coerce_unsized_into<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
278 dst: PlaceRef<'tcx>) {
279 let src_ty = src.layout.ty;
280 let dst_ty = dst.layout.ty;
281 let coerce_ptr = || {
282 let (base, info) = match src.load(bx).val {
283 OperandValue::Pair(base, info) => {
284 // fat-ptr to fat-ptr unsize preserves the vtable
285 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
286 // So we need to pointercast the base to ensure
287 // the types match up.
288 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
289 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
291 OperandValue::Immediate(base) => {
292 unsize_thin_ptr(bx, base, src_ty, dst_ty)
294 OperandValue::Ref(..) => bug!()
296 OperandValue::Pair(base, info).store(bx, dst);
298 match (&src_ty.sty, &dst_ty.sty) {
299 (&ty::TyRef(..), &ty::TyRef(..)) |
300 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
301 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
304 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
308 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
309 assert_eq!(def_a, def_b);
311 for i in 0..def_a.variants[0].fields.len() {
312 let src_f = src.project_field(bx, i);
313 let dst_f = dst.project_field(bx, i);
315 if dst_f.layout.is_zst() {
319 if src_f.layout.ty == dst_f.layout.ty {
320 memcpy_ty(bx, dst_f.llval, src_f.llval, src_f.layout,
321 src_f.align.min(dst_f.align));
323 coerce_unsized_into(bx, src_f, dst_f);
327 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
333 pub fn cast_shift_expr_rhs(
334 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
336 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
339 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
345 where F: FnOnce(ValueRef, Type) -> ValueRef,
346 G: FnOnce(ValueRef, Type) -> ValueRef
348 // Shifts may have any size int on the rhs
350 let mut rhs_llty = val_ty(rhs);
351 let mut lhs_llty = val_ty(lhs);
352 if rhs_llty.kind() == Vector {
353 rhs_llty = rhs_llty.element_type()
355 if lhs_llty.kind() == Vector {
356 lhs_llty = lhs_llty.element_type()
358 let rhs_sz = rhs_llty.int_width();
359 let lhs_sz = lhs_llty.int_width();
362 } else if lhs_sz > rhs_sz {
363 // FIXME (#1877: If shifting by negative
364 // values becomes not undefined then this is wrong.
374 /// Returns whether this session's target will use SEH-based unwinding.
376 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
377 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
378 /// 64-bit MinGW) instead of "full SEH".
379 pub fn wants_msvc_seh(sess: &Session) -> bool {
380 sess.target.target.options.is_like_msvc
383 pub fn call_assume<'a, 'tcx>(bx: &Builder<'a, 'tcx>, val: ValueRef) {
384 let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
385 bx.call(assume_intrinsic, &[val], None);
388 pub fn from_immediate(bx: &Builder, val: ValueRef) -> ValueRef {
389 if val_ty(val) == Type::i1(bx.cx) {
390 bx.zext(val, Type::i8(bx.cx))
396 pub fn to_immediate(bx: &Builder, val: ValueRef, layout: layout::TyLayout) -> ValueRef {
397 if let layout::Abi::Scalar(ref scalar) = layout.abi {
398 if scalar.is_bool() {
399 return bx.trunc(val, Type::i1(bx.cx));
405 pub fn call_memcpy(bx: &Builder,
411 let ptr_width = &cx.sess().target.target.target_pointer_width;
412 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
413 let memcpy = cx.get_intrinsic(&key);
414 let src_ptr = bx.pointercast(src, Type::i8p(cx));
415 let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
416 let size = bx.intcast(n_bytes, cx.isize_ty, false);
417 let align = C_i32(cx, align.abi() as i32);
418 let volatile = C_bool(cx, false);
419 bx.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
422 pub fn memcpy_ty<'a, 'tcx>(
423 bx: &Builder<'a, 'tcx>,
426 layout: TyLayout<'tcx>,
429 let size = layout.size.bytes();
434 call_memcpy(bx, dst, src, C_usize(bx.cx, size), align);
437 pub fn call_memset<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
442 volatile: bool) -> ValueRef {
443 let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
444 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
445 let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
446 let volatile = C_bool(bx.cx, volatile);
447 bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
450 pub fn trans_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
451 let _s = if cx.sess().trans_stats() {
452 let mut instance_name = String::new();
453 DefPathBasedNames::new(cx.tcx, true, true)
454 .push_def_path(instance.def_id(), &mut instance_name);
455 Some(StatRecorder::new(cx, instance_name))
460 // this is an info! to allow collecting monomorphization statistics
461 // and to allow finding the last function before LLVM aborts from
463 info!("trans_instance({})", instance);
465 let fn_ty = instance.ty(cx.tcx);
466 let sig = common::ty_fn_sig(cx, fn_ty);
467 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
469 let lldecl = match cx.instances.borrow().get(&instance) {
471 None => bug!("Instance `{:?}` not already declared", instance)
474 cx.stats.borrow_mut().n_closures += 1;
476 // The `uwtable` attribute according to LLVM is:
478 // This attribute indicates that the ABI being targeted requires that an
479 // unwind table entry be produced for this function even if we can show
480 // that no exceptions passes by it. This is normally the case for the
481 // ELF x86-64 abi, but it can be disabled for some compilation units.
483 // Typically when we're compiling with `-C panic=abort` (which implies this
484 // `no_landing_pads` check) we don't need `uwtable` because we can't
485 // generate any exceptions! On Windows, however, exceptions include other
486 // events such as illegal instructions, segfaults, etc. This means that on
487 // Windows we end up still needing the `uwtable` attribute even if the `-C
488 // panic=abort` flag is passed.
490 // You can also find more info on why Windows is whitelisted here in:
491 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
492 if !cx.sess().no_landing_pads() ||
493 cx.sess().target.target.options.is_like_windows {
494 attributes::emit_uwtable(lldecl, true);
497 let mir = cx.tcx.instance_mir(instance.def);
498 mir::trans_mir(cx, lldecl, &mir, instance, sig);
501 pub fn set_link_section(cx: &CodegenCx,
503 attrs: &[ast::Attribute]) {
504 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
505 if contains_null(§.as_str()) {
506 cx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
509 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
510 llvm::LLVMSetSection(llval, buf.as_ptr());
515 /// Create the `main` function which will initialize the rust runtime and call
516 /// users main function.
517 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
518 let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
519 Some((id, span)) => {
520 (cx.tcx.hir.local_def_id(id), span)
525 let instance = Instance::mono(cx.tcx, main_def_id);
527 if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
528 // We want to create the wrapper in the same codegen unit as Rust's main
533 let main_llfn = callee::get_fn(cx, instance);
535 let et = cx.sess().entry_type.get().unwrap();
537 config::EntryMain => create_entry_fn(cx, span, main_llfn, main_def_id, true),
538 config::EntryStart => create_entry_fn(cx, span, main_llfn, main_def_id, false),
539 config::EntryNone => {} // Do nothing.
542 fn create_entry_fn<'cx>(cx: &'cx CodegenCx,
545 rust_main_def_id: DefId,
546 use_start_lang_item: bool) {
547 let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], &Type::c_int(cx));
549 let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
550 // Given that `main()` has no arguments,
551 // then its return type cannot have
552 // late-bound regions, since late-bound
553 // regions must appear in the argument
555 let main_ret_ty = main_ret_ty.no_late_bound_regions().unwrap();
557 if declare::get_defined_value(cx, "main").is_some() {
558 // FIXME: We should be smart and show a better diagnostic here.
559 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
560 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
562 cx.sess().abort_if_errors();
565 let llfn = declare::declare_cfn(cx, "main", llfty);
567 // `main` should respect same config for frame pointer elimination as rest of code
568 attributes::set_frame_pointer_elimination(cx, llfn);
570 let bx = Builder::new_block(cx, llfn, "top");
572 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
574 // Params from native main() used as args for rust start function
575 let param_argc = get_param(llfn, 0);
576 let param_argv = get_param(llfn, 1);
577 let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
578 let arg_argv = param_argv;
580 let (start_fn, args) = if use_start_lang_item {
581 let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
582 let start_fn = callee::resolve_and_get_fn(cx, start_def_id, cx.tcx.mk_substs(
583 iter::once(Kind::from(main_ret_ty))));
584 (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
587 debug!("using user-defined start fn");
588 (rust_main, vec![arg_argc, arg_argv])
591 let result = bx.call(start_fn, &args, None);
592 bx.ret(bx.intcast(result, Type::c_int(cx), true));
596 fn contains_null(s: &str) -> bool {
597 s.bytes().any(|b| b == 0)
600 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
602 link_meta: &LinkMeta)
603 -> (ContextRef, ModuleRef, EncodedMetadata) {
605 use flate2::Compression;
606 use flate2::write::DeflateEncoder;
608 let (metadata_llcx, metadata_llmod) = unsafe {
609 context::create_context_and_module(tcx.sess, llmod_id)
612 #[derive(PartialEq, Eq, PartialOrd, Ord)]
619 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
621 config::CrateTypeExecutable |
622 config::CrateTypeStaticlib |
623 config::CrateTypeCdylib => MetadataKind::None,
625 config::CrateTypeRlib => MetadataKind::Uncompressed,
627 config::CrateTypeDylib |
628 config::CrateTypeProcMacro => MetadataKind::Compressed,
632 if kind == MetadataKind::None {
633 return (metadata_llcx,
635 EncodedMetadata::new());
638 let metadata = tcx.encode_metadata(link_meta);
639 if kind == MetadataKind::Uncompressed {
640 return (metadata_llcx, metadata_llmod, metadata);
643 assert!(kind == MetadataKind::Compressed);
644 let mut compressed = tcx.metadata_encoding_version();
645 DeflateEncoder::new(&mut compressed, Compression::fast())
646 .write_all(&metadata.raw_data).unwrap();
648 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
649 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
650 let name = exported_symbols::metadata_symbol_name(tcx);
651 let buf = CString::new(name).unwrap();
652 let llglobal = unsafe {
653 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
656 llvm::LLVMSetInitializer(llglobal, llconst);
657 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
658 let name = CString::new(section_name).unwrap();
659 llvm::LLVMSetSection(llglobal, name.as_ptr());
661 // Also generate a .section directive to force no
662 // flags, at least for ELF outputs, so that the
663 // metadata doesn't get loaded into memory.
664 let directive = format!(".section {}", section_name);
665 let directive = CString::new(directive).unwrap();
666 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
668 return (metadata_llcx, metadata_llmod, metadata);
671 pub struct ValueIter {
673 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
676 impl Iterator for ValueIter {
677 type Item = ValueRef;
679 fn next(&mut self) -> Option<ValueRef> {
682 self.cur = unsafe { (self.step)(old) };
690 pub fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
693 cur: llvm::LLVMGetFirstGlobal(llmod),
694 step: llvm::LLVMGetNextGlobal,
699 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
700 rx: mpsc::Receiver<Box<Any + Send>>)
701 -> OngoingCrateTranslation {
703 check_for_rustc_errors_attr(tcx);
705 if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
706 if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
707 tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
711 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
712 let link_meta = link::build_link_meta(crate_hash);
714 // Translate the metadata.
715 let llmod_id = "metadata";
716 let (metadata_llcx, metadata_llmod, metadata) =
717 time(tcx.sess, "write metadata", || {
718 write_metadata(tcx, llmod_id, &link_meta)
721 let metadata_module = ModuleTranslation {
722 name: link::METADATA_MODULE_NAME.to_string(),
723 llmod_id: llmod_id.to_string(),
724 source: ModuleSource::Translated(ModuleLlvm {
726 llmod: metadata_llmod,
727 tm: create_target_machine(tcx.sess),
729 kind: ModuleKind::Metadata,
732 let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
733 Some(time_graph::TimeGraph::new())
738 // Skip crate items and just output metadata in -Z no-trans mode.
739 if tcx.sess.opts.debugging_opts.no_trans ||
740 !tcx.sess.opts.output_types.should_trans() {
741 let ongoing_translation = write::start_async_translation(
749 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
750 ongoing_translation.translation_finished(tcx);
752 assert_and_save_dep_graph(tcx);
754 ongoing_translation.check_for_errors(tcx.sess);
756 return ongoing_translation;
759 // Run the translation item collector and partition the collected items into
762 tcx.collect_and_partition_translation_items(LOCAL_CRATE).1;
763 let codegen_units = (*codegen_units).clone();
765 // Force all codegen_unit queries so they are already either red or green
766 // when compile_codegen_unit accesses them. We are not able to re-execute
767 // the codegen_unit query from just the DepNode, so an unknown color would
768 // lead to having to re-execute compile_codegen_unit, possibly
770 if tcx.dep_graph.is_fully_enabled() {
771 for cgu in &codegen_units {
772 tcx.codegen_unit(cgu.name().clone());
776 let ongoing_translation = write::start_async_translation(
782 codegen_units.len());
784 // Translate an allocator shim, if any
785 let allocator_module = if let Some(kind) = tcx.sess.allocator_kind.get() {
787 let llmod_id = "allocator";
789 context::create_context_and_module(tcx.sess, llmod_id);
790 let modules = ModuleLlvm {
793 tm: create_target_machine(tcx.sess),
795 time(tcx.sess, "write allocator module", || {
796 allocator::trans(tcx, &modules, kind)
799 Some(ModuleTranslation {
800 name: link::ALLOCATOR_MODULE_NAME.to_string(),
801 llmod_id: llmod_id.to_string(),
802 source: ModuleSource::Translated(modules),
803 kind: ModuleKind::Allocator,
810 if let Some(allocator_module) = allocator_module {
811 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, allocator_module);
814 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
816 // We sort the codegen units by size. This way we can schedule work for LLVM
817 // a bit more efficiently.
818 let codegen_units = {
819 let mut codegen_units = codegen_units;
820 codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
824 let mut total_trans_time = Duration::new(0, 0);
825 let mut all_stats = Stats::default();
827 for cgu in codegen_units.into_iter() {
828 ongoing_translation.wait_for_signal_to_translate_item();
829 ongoing_translation.check_for_errors(tcx.sess);
831 // First, if incremental compilation is enabled, we try to re-use the
832 // codegen unit from the cache.
833 if tcx.dep_graph.is_fully_enabled() {
834 let cgu_id = cgu.work_product_id();
836 // Check whether there is a previous work-product we can
837 // re-use. Not only must the file exist, and the inputs not
838 // be dirty, but the hash of the symbols we will generate must
840 if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
841 let dep_node = &DepNode::new(tcx,
842 DepConstructor::CompileCodegenUnit(cgu.name().clone()));
844 // We try to mark the DepNode::CompileCodegenUnit green. If we
845 // succeed it means that none of the dependencies has changed
846 // and we can safely re-use.
847 if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
848 // Append ".rs" to LLVM module identifier.
850 // LLVM code generator emits a ".file filename" directive
851 // for ELF backends. Value of the "filename" is set as the
852 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
853 // crashes if the module identifier is same as other symbols
854 // such as a function name in the module.
855 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
856 let llmod_id = format!("{}.rs", cgu.name());
858 let module = ModuleTranslation {
859 name: cgu.name().to_string(),
860 source: ModuleSource::Preexisting(buf),
861 kind: ModuleKind::Regular,
864 tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
865 write::submit_translated_module_to_llvm(tcx, module, 0);
866 // Continue to next cgu, this one is done.
870 // This can happen if files were deleted from the cache
871 // directory for some reason. We just re-compile then.
875 let _timing_guard = time_graph.as_ref().map(|time_graph| {
876 time_graph.start(write::TRANS_WORKER_TIMELINE,
877 write::TRANS_WORK_PACKAGE_KIND,
878 &format!("codegen {}", cgu.name()))
880 let start_time = Instant::now();
881 all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
882 total_trans_time += start_time.elapsed();
883 ongoing_translation.check_for_errors(tcx.sess);
886 ongoing_translation.translation_finished(tcx);
888 // Since the main thread is sometimes blocked during trans, we keep track
889 // -Ztime-passes output manually.
890 print_time_passes_entry(tcx.sess.time_passes(),
891 "translate to LLVM IR",
894 if tcx.sess.opts.incremental.is_some() {
895 ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
898 symbol_names_test::report_symbol_names(tcx);
900 if tcx.sess.trans_stats() {
901 println!("--- trans stats ---");
902 println!("n_glues_created: {}", all_stats.n_glues_created);
903 println!("n_null_glues: {}", all_stats.n_null_glues);
904 println!("n_real_glues: {}", all_stats.n_real_glues);
906 println!("n_fns: {}", all_stats.n_fns);
907 println!("n_inlines: {}", all_stats.n_inlines);
908 println!("n_closures: {}", all_stats.n_closures);
909 println!("fn stats:");
910 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
911 for &(ref name, insns) in all_stats.fn_stats.iter() {
912 println!("{} insns, {}", insns, *name);
916 if tcx.sess.count_llvm_insns() {
917 for (k, v) in all_stats.llvm_insns.iter() {
918 println!("{:7} {}", *v, *k);
922 ongoing_translation.check_for_errors(tcx.sess);
924 assert_and_save_dep_graph(tcx);
928 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
931 || rustc_incremental::assert_dep_graph(tcx));
934 "serialize dep graph",
935 || rustc_incremental::save_dep_graph(tcx));
938 fn collect_and_partition_translation_items<'a, 'tcx>(
939 tcx: TyCtxt<'a, 'tcx, 'tcx>,
941 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
943 assert_eq!(cnum, LOCAL_CRATE);
945 let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
947 let mode_string = s.to_lowercase();
948 let mode_string = mode_string.trim();
949 if mode_string == "eager" {
950 MonoItemCollectionMode::Eager
952 if mode_string != "lazy" {
953 let message = format!("Unknown codegen-item collection mode '{}'. \
954 Falling back to 'lazy' mode.",
956 tcx.sess.warn(&message);
959 MonoItemCollectionMode::Lazy
963 if tcx.sess.opts.cg.link_dead_code {
964 MonoItemCollectionMode::Eager
966 MonoItemCollectionMode::Lazy
971 let (items, inlining_map) =
972 time(tcx.sess, "translation item collection", || {
973 collector::collect_crate_mono_items(tcx, collection_mode)
976 tcx.sess.abort_if_errors();
978 ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
980 let strategy = if tcx.sess.opts.incremental.is_some() {
981 PartitioningStrategy::PerModule
983 PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
986 let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
987 partitioning::partition(tcx,
988 items.iter().cloned(),
996 let translation_items: DefIdSet = items.iter().filter_map(|trans_item| {
998 MonoItem::Fn(ref instance) => Some(instance.def_id()),
999 MonoItem::Static(def_id) => Some(def_id),
1004 if tcx.sess.opts.debugging_opts.print_trans_items.is_some() {
1005 let mut item_to_cgus = FxHashMap();
1007 for cgu in &codegen_units {
1008 for (&trans_item, &linkage) in cgu.items() {
1009 item_to_cgus.entry(trans_item)
1010 .or_insert(Vec::new())
1011 .push((cgu.name().clone(), linkage));
1015 let mut item_keys: Vec<_> = items
1018 let mut output = i.to_string(tcx);
1019 output.push_str(" @@");
1020 let mut empty = Vec::new();
1021 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1022 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1024 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1025 output.push_str(" ");
1026 output.push_str(&cgu_name);
1028 let linkage_abbrev = match linkage {
1029 Linkage::External => "External",
1030 Linkage::AvailableExternally => "Available",
1031 Linkage::LinkOnceAny => "OnceAny",
1032 Linkage::LinkOnceODR => "OnceODR",
1033 Linkage::WeakAny => "WeakAny",
1034 Linkage::WeakODR => "WeakODR",
1035 Linkage::Appending => "Appending",
1036 Linkage::Internal => "Internal",
1037 Linkage::Private => "Private",
1038 Linkage::ExternalWeak => "ExternalWeak",
1039 Linkage::Common => "Common",
1042 output.push_str("[");
1043 output.push_str(linkage_abbrev);
1044 output.push_str("]");
1052 for item in item_keys {
1053 println!("TRANS_ITEM {}", item);
1057 (Arc::new(translation_items), Arc::new(codegen_units))
1061 pub fn new(tcx: TyCtxt) -> CrateInfo {
1062 let mut info = CrateInfo {
1063 panic_runtime: None,
1064 compiler_builtins: None,
1065 profiler_runtime: None,
1066 sanitizer_runtime: None,
1067 is_no_builtins: FxHashSet(),
1068 native_libraries: FxHashMap(),
1069 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1070 link_args: tcx.link_args(LOCAL_CRATE),
1071 crate_name: FxHashMap(),
1072 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1073 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1074 used_crate_source: FxHashMap(),
1075 wasm_custom_sections: BTreeMap::new(),
1076 wasm_imports: FxHashMap(),
1079 let load_wasm_items = tcx.sess.crate_types.borrow()
1081 .any(|c| *c != config::CrateTypeRlib) &&
1082 tcx.sess.opts.target_triple == "wasm32-unknown-unknown";
1084 if load_wasm_items {
1085 info!("attempting to load all wasm sections");
1086 for &id in tcx.wasm_custom_sections(LOCAL_CRATE).iter() {
1087 let (name, contents) = fetch_wasm_section(tcx, id);
1088 info.wasm_custom_sections.entry(name)
1089 .or_insert(Vec::new())
1092 info.load_wasm_imports(tcx, LOCAL_CRATE);
1095 for &cnum in tcx.crates().iter() {
1096 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1097 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1098 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1099 if tcx.is_panic_runtime(cnum) {
1100 info.panic_runtime = Some(cnum);
1102 if tcx.is_compiler_builtins(cnum) {
1103 info.compiler_builtins = Some(cnum);
1105 if tcx.is_profiler_runtime(cnum) {
1106 info.profiler_runtime = Some(cnum);
1108 if tcx.is_sanitizer_runtime(cnum) {
1109 info.sanitizer_runtime = Some(cnum);
1111 if tcx.is_no_builtins(cnum) {
1112 info.is_no_builtins.insert(cnum);
1114 if load_wasm_items {
1115 for &id in tcx.wasm_custom_sections(cnum).iter() {
1116 let (name, contents) = fetch_wasm_section(tcx, id);
1117 info.wasm_custom_sections.entry(name)
1118 .or_insert(Vec::new())
1121 info.load_wasm_imports(tcx, cnum);
1128 fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1129 for (&id, module) in tcx.wasm_import_module_map(cnum).iter() {
1130 let instance = Instance::mono(tcx, id);
1131 let import_name = tcx.symbol_name(instance);
1132 self.wasm_imports.insert(import_name.to_string(), module.clone());
1137 fn is_translated_item(tcx: TyCtxt, id: DefId) -> bool {
1138 let (all_trans_items, _) =
1139 tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1140 all_trans_items.contains(&id)
1143 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1144 cgu: InternedString) -> Stats {
1145 let cgu = tcx.codegen_unit(cgu);
1147 let start_time = Instant::now();
1148 let (stats, module) = module_translation(tcx, cgu);
1149 let time_to_translate = start_time.elapsed();
1151 // We assume that the cost to run LLVM on a CGU is proportional to
1152 // the time we needed for translating it.
1153 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1154 time_to_translate.subsec_nanos() as u64;
1156 write::submit_translated_module_to_llvm(tcx,
1161 fn module_translation<'a, 'tcx>(
1162 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1163 cgu: Arc<CodegenUnit<'tcx>>)
1164 -> (Stats, ModuleTranslation)
1166 let cgu_name = cgu.name().to_string();
1168 // Append ".rs" to LLVM module identifier.
1170 // LLVM code generator emits a ".file filename" directive
1171 // for ELF backends. Value of the "filename" is set as the
1172 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
1173 // crashes if the module identifier is same as other symbols
1174 // such as a function name in the module.
1175 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
1176 let llmod_id = format!("{}-{}.rs",
1178 tcx.crate_disambiguator(LOCAL_CRATE)
1179 .to_fingerprint().to_hex());
1181 // Instantiate translation items without filling out definitions yet...
1182 let cx = CodegenCx::new(tcx, cgu, &llmod_id);
1184 let trans_items = cx.codegen_unit
1185 .items_in_deterministic_order(cx.tcx);
1186 for &(trans_item, (linkage, visibility)) in &trans_items {
1187 trans_item.predefine(&cx, linkage, visibility);
1190 // ... and now that we have everything pre-defined, fill out those definitions.
1191 for &(trans_item, _) in &trans_items {
1192 trans_item.define(&cx);
1195 // If this codegen unit contains the main function, also create the
1197 maybe_create_entry_wrapper(&cx);
1199 // Run replace-all-uses-with for statics that need it
1200 for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1202 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1203 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1204 llvm::LLVMDeleteGlobal(old_g);
1208 // Create the llvm.used variable
1209 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1210 if !cx.used_statics.borrow().is_empty() {
1211 let name = CString::new("llvm.used").unwrap();
1212 let section = CString::new("llvm.metadata").unwrap();
1213 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1216 let g = llvm::LLVMAddGlobal(cx.llmod,
1217 val_ty(array).to_ref(),
1219 llvm::LLVMSetInitializer(g, array);
1220 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1221 llvm::LLVMSetSection(g, section.as_ptr());
1225 // Finalize debuginfo
1226 if cx.sess().opts.debuginfo != NoDebugInfo {
1227 debuginfo::finalize(&cx);
1230 let llvm_module = ModuleLlvm {
1233 tm: create_target_machine(cx.sess()),
1238 source: ModuleSource::Translated(llvm_module),
1239 kind: ModuleKind::Regular,
1244 (cx.into_stats(), module)
1248 pub fn provide(providers: &mut Providers) {
1249 providers.collect_and_partition_translation_items =
1250 collect_and_partition_translation_items;
1252 providers.is_translated_item = is_translated_item;
1254 providers.codegen_unit = |tcx, name| {
1255 let (_, all) = tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1257 .find(|cgu| *cgu.name() == name)
1259 .expect(&format!("failed to find cgu with name {:?}", name))
1261 providers.compile_codegen_unit = compile_codegen_unit;
1263 provide_extern(providers);
1266 pub fn provide_extern(providers: &mut Providers) {
1267 providers.dllimport_foreign_items = |tcx, krate| {
1268 let module_map = tcx.foreign_modules(krate);
1269 let module_map = module_map.iter()
1270 .map(|lib| (lib.def_id, lib))
1271 .collect::<FxHashMap<_, _>>();
1273 let dllimports = tcx.native_libraries(krate)
1276 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1279 let cfg = match lib.cfg {
1280 Some(ref cfg) => cfg,
1281 None => return true,
1283 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1285 .filter_map(|lib| lib.foreign_module)
1286 .map(|id| &module_map[&id])
1287 .flat_map(|module| module.foreign_items.iter().cloned())
1289 Lrc::new(dllimports)
1292 providers.is_dllimport_foreign_item = |tcx, def_id| {
1293 tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1297 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1299 Linkage::External => llvm::Linkage::ExternalLinkage,
1300 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1301 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1302 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1303 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1304 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1305 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1306 Linkage::Internal => llvm::Linkage::InternalLinkage,
1307 Linkage::Private => llvm::Linkage::PrivateLinkage,
1308 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1309 Linkage::Common => llvm::Linkage::CommonLinkage,
1313 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1315 Visibility::Default => llvm::Visibility::Default,
1316 Visibility::Hidden => llvm::Visibility::Hidden,
1317 Visibility::Protected => llvm::Visibility::Protected,
1321 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1322 // the HashStable trait. Normally DepGraph::with_task() calls are
1323 // hidden behind queries, but CGU creation is a special case in two
1324 // ways: (1) it's not a query and (2) CGU are output nodes, so their
1325 // Fingerprints are not actually needed. It remains to be clarified
1326 // how exactly this case will be handled in the red/green system but
1327 // for now we content ourselves with providing a no-op HashStable
1328 // implementation for CGUs.
1329 mod temp_stable_hash_impls {
1330 use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1332 use ModuleTranslation;
1334 impl<HCX> HashStable<HCX> for ModuleTranslation {
1335 fn hash_stable<W: StableHasherResult>(&self,
1337 _: &mut StableHasher<W>) {
1343 fn fetch_wasm_section(tcx: TyCtxt, id: DefId) -> (String, Vec<u8>) {
1344 use rustc::mir::interpret::{GlobalId, Value, PrimVal};
1345 use rustc::middle::const_val::ConstVal;
1347 info!("loading wasm section {:?}", id);
1349 let section = tcx.get_attrs(id)
1351 .find(|a| a.check_name("wasm_custom_section"))
1352 .expect("missing #[wasm_custom_section] attribute")
1354 .expect("malformed #[wasm_custom_section] attribute");
1356 let instance = ty::Instance::mono(tcx, id);
1357 let cid = GlobalId {
1361 let param_env = ty::ParamEnv::reveal_all();
1362 let val = tcx.const_eval(param_env.and(cid)).unwrap();
1364 let val = match val.val {
1365 ConstVal::Value(val) => val,
1366 ConstVal::Unevaluated(..) => bug!("should be evaluated"),
1368 let val = match val {
1369 Value::ByRef(ptr, _align) => ptr.into_inner_primval(),
1370 ref v => bug!("should be ByRef, was {:?}", v),
1372 let mem = match val {
1373 PrimVal::Ptr(mem) => mem,
1374 ref v => bug!("should be Ptr, was {:?}", v),
1376 assert_eq!(mem.offset, 0);
1379 .get_alloc(mem.alloc_id)
1380 .expect("miri allocation never successfully created");
1381 (section.to_string(), alloc.bytes.clone())