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;
32 use assert_module_sources;
34 use back::symbol_export;
35 use back::write::{self, OngoingCrateTranslation, create_target_machine};
36 use llvm::{ContextRef, ModuleRef, ValueRef, Vector, get_param};
39 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
40 use rustc::middle::lang_items::StartFnLangItem;
41 use rustc::mir::mono::{Linkage, Visibility, Stats};
42 use rustc::middle::cstore::{EncodedMetadata};
43 use rustc::ty::{self, Ty, TyCtxt};
44 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf};
45 use rustc::ty::maps::Providers;
46 use rustc::dep_graph::{DepNode, DepKind, DepConstructor};
47 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
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, CrateContext, val_ty};
61 use context::{self, LocalCrateContext, SharedCrateContext};
66 use monomorphize::Instance;
67 use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
68 use symbol_names_test;
70 use trans_item::{MonoItem, BaseMonoItemExt, MonoItemExt, DefPathBasedNames};
72 use type_of::LayoutLlvmExt;
73 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet, DefIdSet};
77 use std::ffi::CString;
80 use std::time::{Instant, Duration};
84 use syntax_pos::symbol::InternedString;
89 use mir::operand::OperandValue;
91 pub use rustc_trans_utils::{find_exported_symbols, check_for_rustc_errors_attr};
92 pub use rustc_mir::monomorphize::item::linkage_by_name;
94 pub struct StatRecorder<'a, 'tcx: 'a> {
95 ccx: &'a CrateContext<'a, 'tcx>,
100 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
101 pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
102 let istart = ccx.stats().borrow().n_llvm_insns;
111 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
113 if self.ccx.sess().trans_stats() {
114 let mut stats = self.ccx.stats().borrow_mut();
115 let iend = stats.n_llvm_insns;
116 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
118 // Reset LLVM insn count to avoid compound costs.
119 stats.n_llvm_insns = self.istart;
124 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
126 -> llvm::IntPredicate {
128 hir::BiEq => llvm::IntEQ,
129 hir::BiNe => llvm::IntNE,
130 hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
131 hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
132 hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
133 hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
135 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
142 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
144 hir::BiEq => llvm::RealOEQ,
145 hir::BiNe => llvm::RealUNE,
146 hir::BiLt => llvm::RealOLT,
147 hir::BiLe => llvm::RealOLE,
148 hir::BiGt => llvm::RealOGT,
149 hir::BiGe => llvm::RealOGE,
151 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
158 pub fn compare_simd_types<'a, 'tcx>(
159 bcx: &Builder<'a, 'tcx>,
166 let signed = match t.sty {
168 let cmp = bin_op_to_fcmp_predicate(op);
169 return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
171 ty::TyUint(_) => false,
172 ty::TyInt(_) => true,
173 _ => bug!("compare_simd_types: invalid SIMD type"),
176 let cmp = bin_op_to_icmp_predicate(op, signed);
177 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
178 // to get the correctly sized type. This will compile to a single instruction
179 // once the IR is converted to assembly if the SIMD instruction is supported
180 // by the target architecture.
181 bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
184 /// Retrieve the information we are losing (making dynamic) in an unsizing
187 /// The `old_info` argument is a bit funny. It is intended for use
188 /// in an upcast, where the new vtable for an object will be derived
189 /// from the old one.
190 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
193 old_info: Option<ValueRef>)
195 let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
196 match (&source.sty, &target.sty) {
197 (&ty::TyArray(_, len), &ty::TySlice(_)) => {
198 C_usize(ccx, len.val.to_const_int().unwrap().to_u64().unwrap())
200 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
201 // For now, upcasts are limited to changes in marker
202 // traits, and hence never actually require an actual
203 // change to the vtable.
204 old_info.expect("unsized_info: missing old info for trait upcast")
206 (_, &ty::TyDynamic(ref data, ..)) => {
207 let vtable_ptr = ccx.layout_of(ccx.tcx().mk_mut_ptr(target))
208 .field(ccx, abi::FAT_PTR_EXTRA);
209 consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
210 vtable_ptr.llvm_type(ccx))
212 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
218 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
219 pub fn unsize_thin_ptr<'a, 'tcx>(
220 bcx: &Builder<'a, 'tcx>,
224 ) -> (ValueRef, ValueRef) {
225 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
226 match (&src_ty.sty, &dst_ty.sty) {
227 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
228 &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
229 (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
230 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
231 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
232 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
233 assert!(bcx.ccx.shared().type_is_sized(a));
234 let ptr_ty = bcx.ccx.layout_of(b).llvm_type(bcx.ccx).ptr_to();
235 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
237 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
238 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
239 assert!(bcx.ccx.shared().type_is_sized(a));
240 let ptr_ty = bcx.ccx.layout_of(b).llvm_type(bcx.ccx).ptr_to();
241 (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
243 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
244 assert_eq!(def_a, def_b);
246 let src_layout = bcx.ccx.layout_of(src_ty);
247 let dst_layout = bcx.ccx.layout_of(dst_ty);
248 let mut result = None;
249 for i in 0..src_layout.fields.count() {
250 let src_f = src_layout.field(bcx.ccx, i);
251 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
252 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
256 assert_eq!(src_layout.size, src_f.size);
258 let dst_f = dst_layout.field(bcx.ccx, i);
259 assert_ne!(src_f.ty, dst_f.ty);
260 assert_eq!(result, None);
261 result = Some(unsize_thin_ptr(bcx, src, src_f.ty, dst_f.ty));
263 let (lldata, llextra) = result.unwrap();
264 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
265 (bcx.bitcast(lldata, dst_layout.scalar_pair_element_llvm_type(bcx.ccx, 0)),
266 bcx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bcx.ccx, 1)))
268 _ => bug!("unsize_thin_ptr: called on bad types"),
272 /// Coerce `src`, which is a reference to a value of type `src_ty`,
273 /// to a value of type `dst_ty` and store the result in `dst`
274 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
276 dst: PlaceRef<'tcx>) {
277 let src_ty = src.layout.ty;
278 let dst_ty = dst.layout.ty;
279 let coerce_ptr = || {
280 let (base, info) = match src.load(bcx).val {
281 OperandValue::Pair(base, info) => {
282 // fat-ptr to fat-ptr unsize preserves the vtable
283 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
284 // So we need to pointercast the base to ensure
285 // the types match up.
286 let thin_ptr = dst.layout.field(bcx.ccx, abi::FAT_PTR_ADDR);
287 (bcx.pointercast(base, thin_ptr.llvm_type(bcx.ccx)), info)
289 OperandValue::Immediate(base) => {
290 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
292 OperandValue::Ref(..) => bug!()
294 OperandValue::Pair(base, info).store(bcx, dst);
296 match (&src_ty.sty, &dst_ty.sty) {
297 (&ty::TyRef(..), &ty::TyRef(..)) |
298 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
299 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
302 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
306 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
307 assert_eq!(def_a, def_b);
309 for i in 0..def_a.variants[0].fields.len() {
310 let src_f = src.project_field(bcx, i);
311 let dst_f = dst.project_field(bcx, i);
313 if dst_f.layout.is_zst() {
317 if src_f.layout.ty == dst_f.layout.ty {
318 memcpy_ty(bcx, dst_f.llval, src_f.llval, src_f.layout,
319 src_f.align.min(dst_f.align));
321 coerce_unsized_into(bcx, src_f, dst_f);
325 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
331 pub fn cast_shift_expr_rhs(
332 cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
334 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
337 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
341 |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
342 |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
345 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
351 where F: FnOnce(ValueRef, Type) -> ValueRef,
352 G: FnOnce(ValueRef, Type) -> ValueRef
354 // Shifts may have any size int on the rhs
356 let mut rhs_llty = val_ty(rhs);
357 let mut lhs_llty = val_ty(lhs);
358 if rhs_llty.kind() == Vector {
359 rhs_llty = rhs_llty.element_type()
361 if lhs_llty.kind() == Vector {
362 lhs_llty = lhs_llty.element_type()
364 let rhs_sz = rhs_llty.int_width();
365 let lhs_sz = lhs_llty.int_width();
368 } else if lhs_sz > rhs_sz {
369 // FIXME (#1877: If shifting by negative
370 // values becomes not undefined then this is wrong.
380 /// Returns whether this session's target will use SEH-based unwinding.
382 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
383 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
384 /// 64-bit MinGW) instead of "full SEH".
385 pub fn wants_msvc_seh(sess: &Session) -> bool {
386 sess.target.target.options.is_like_msvc
389 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
390 let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
391 b.call(assume_intrinsic, &[val], None);
394 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
395 if val_ty(val) == Type::i1(bcx.ccx) {
396 bcx.zext(val, Type::i8(bcx.ccx))
402 pub fn to_immediate(bcx: &Builder, val: ValueRef, layout: layout::TyLayout) -> ValueRef {
403 if let layout::Abi::Scalar(ref scalar) = layout.abi {
404 if scalar.is_bool() {
405 return bcx.trunc(val, Type::i1(bcx.ccx));
411 pub fn call_memcpy(b: &Builder,
417 let ptr_width = &ccx.sess().target.target.target_pointer_width;
418 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
419 let memcpy = ccx.get_intrinsic(&key);
420 let src_ptr = b.pointercast(src, Type::i8p(ccx));
421 let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
422 let size = b.intcast(n_bytes, ccx.isize_ty(), false);
423 let align = C_i32(ccx, align.abi() as i32);
424 let volatile = C_bool(ccx, false);
425 b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
428 pub fn memcpy_ty<'a, 'tcx>(
429 bcx: &Builder<'a, 'tcx>,
432 layout: TyLayout<'tcx>,
435 let size = layout.size.bytes();
440 call_memcpy(bcx, dst, src, C_usize(bcx.ccx, size), align);
443 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
448 volatile: bool) -> ValueRef {
449 let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
450 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
451 let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
452 let volatile = C_bool(b.ccx, volatile);
453 b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
456 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
457 let _s = if ccx.sess().trans_stats() {
458 let mut instance_name = String::new();
459 DefPathBasedNames::new(ccx.tcx(), true, true)
460 .push_def_path(instance.def_id(), &mut instance_name);
461 Some(StatRecorder::new(ccx, instance_name))
466 // this is an info! to allow collecting monomorphization statistics
467 // and to allow finding the last function before LLVM aborts from
469 info!("trans_instance({})", instance);
471 let fn_ty = instance.ty(ccx.tcx());
472 let sig = common::ty_fn_sig(ccx, fn_ty);
473 let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
475 let lldecl = match ccx.instances().borrow().get(&instance) {
477 None => bug!("Instance `{:?}` not already declared", instance)
480 ccx.stats().borrow_mut().n_closures += 1;
482 // The `uwtable` attribute according to LLVM is:
484 // This attribute indicates that the ABI being targeted requires that an
485 // unwind table entry be produced for this function even if we can show
486 // that no exceptions passes by it. This is normally the case for the
487 // ELF x86-64 abi, but it can be disabled for some compilation units.
489 // Typically when we're compiling with `-C panic=abort` (which implies this
490 // `no_landing_pads` check) we don't need `uwtable` because we can't
491 // generate any exceptions! On Windows, however, exceptions include other
492 // events such as illegal instructions, segfaults, etc. This means that on
493 // Windows we end up still needing the `uwtable` attribute even if the `-C
494 // panic=abort` flag is passed.
496 // You can also find more info on why Windows is whitelisted here in:
497 // https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
498 if !ccx.sess().no_landing_pads() ||
499 ccx.sess().target.target.options.is_like_windows {
500 attributes::emit_uwtable(lldecl, true);
503 let mir = ccx.tcx().instance_mir(instance.def);
504 mir::trans_mir(ccx, lldecl, &mir, instance, sig);
507 pub fn set_link_section(ccx: &CrateContext,
509 attrs: &[ast::Attribute]) {
510 if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
511 if contains_null(§.as_str()) {
512 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", §));
515 let buf = CString::new(sect.as_str().as_bytes()).unwrap();
516 llvm::LLVMSetSection(llval, buf.as_ptr());
521 /// Create the `main` function which will initialize the rust runtime and call
522 /// users main function.
523 fn maybe_create_entry_wrapper(ccx: &CrateContext) {
524 let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
525 Some((id, span)) => {
526 (ccx.tcx().hir.local_def_id(id), span)
531 let instance = Instance::mono(ccx.tcx(), main_def_id);
533 if !ccx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
534 // We want to create the wrapper in the same codegen unit as Rust's main
539 let main_llfn = callee::get_fn(ccx, instance);
541 let et = ccx.sess().entry_type.get().unwrap();
543 config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
544 config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
545 config::EntryNone => {} // Do nothing.
548 fn create_entry_fn(ccx: &CrateContext,
551 use_start_lang_item: bool) {
552 // Signature of native main(), corresponding to C's `int main(int, char **)`
553 let llfty = Type::func(&[Type::c_int(ccx), Type::i8p(ccx).ptr_to()], &Type::c_int(ccx));
555 if declare::get_defined_value(ccx, "main").is_some() {
556 // FIXME: We should be smart and show a better diagnostic here.
557 ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
558 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
560 ccx.sess().abort_if_errors();
563 let llfn = declare::declare_cfn(ccx, "main", llfty);
565 // `main` should respect same config for frame pointer elimination as rest of code
566 attributes::set_frame_pointer_elimination(ccx, llfn);
568 let bld = Builder::new_block(ccx, llfn, "top");
570 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
572 // Params from native main() used as args for rust start function
573 let param_argc = get_param(llfn, 0);
574 let param_argv = get_param(llfn, 1);
575 let arg_argc = bld.intcast(param_argc, ccx.isize_ty(), true);
576 let arg_argv = param_argv;
578 let (start_fn, args) = if use_start_lang_item {
579 let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
580 let start_instance = Instance::mono(ccx.tcx(), start_def_id);
581 let start_fn = callee::get_fn(ccx, start_instance);
582 (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()),
585 debug!("using user-defined start fn");
586 (rust_main, vec![arg_argc, arg_argv])
589 let result = bld.call(start_fn, &args, None);
591 // Return rust start function's result from native main()
592 bld.ret(bld.intcast(result, Type::c_int(ccx), 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 exported_symbols: &NodeSet)
604 -> (ContextRef, ModuleRef, EncodedMetadata) {
606 use flate2::Compression;
607 use flate2::write::DeflateEncoder;
609 let (metadata_llcx, metadata_llmod) = unsafe {
610 context::create_context_and_module(tcx.sess, llmod_id)
613 #[derive(PartialEq, Eq, PartialOrd, Ord)]
620 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
622 config::CrateTypeExecutable |
623 config::CrateTypeStaticlib |
624 config::CrateTypeCdylib => MetadataKind::None,
626 config::CrateTypeRlib => MetadataKind::Uncompressed,
628 config::CrateTypeDylib |
629 config::CrateTypeProcMacro => MetadataKind::Compressed,
633 if kind == MetadataKind::None {
634 return (metadata_llcx,
636 EncodedMetadata::new());
639 let metadata = tcx.encode_metadata(link_meta, exported_symbols);
640 if kind == MetadataKind::Uncompressed {
641 return (metadata_llcx, metadata_llmod, metadata);
644 assert!(kind == MetadataKind::Compressed);
645 let mut compressed = tcx.metadata_encoding_version();
646 DeflateEncoder::new(&mut compressed, Compression::Fast)
647 .write_all(&metadata.raw_data).unwrap();
649 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
650 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
651 let name = symbol_export::metadata_symbol_name(tcx);
652 let buf = CString::new(name).unwrap();
653 let llglobal = unsafe {
654 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
657 llvm::LLVMSetInitializer(llglobal, llconst);
658 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
659 let name = CString::new(section_name).unwrap();
660 llvm::LLVMSetSection(llglobal, name.as_ptr());
662 // Also generate a .section directive to force no
663 // flags, at least for ELF outputs, so that the
664 // metadata doesn't get loaded into memory.
665 let directive = format!(".section {}", section_name);
666 let directive = CString::new(directive).unwrap();
667 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
669 return (metadata_llcx, metadata_llmod, metadata);
672 pub struct ValueIter {
674 step: unsafe extern "C" fn(ValueRef) -> ValueRef,
677 impl Iterator for ValueIter {
678 type Item = ValueRef;
680 fn next(&mut self) -> Option<ValueRef> {
683 self.cur = unsafe { (self.step)(old) };
691 pub fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
694 cur: llvm::LLVMGetFirstGlobal(llmod),
695 step: llvm::LLVMGetNextGlobal,
700 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
701 rx: mpsc::Receiver<Box<Any + Send>>)
702 -> OngoingCrateTranslation {
704 check_for_rustc_errors_attr(tcx);
706 if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
707 if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
708 tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
712 let crate_hash = tcx.dep_graph
713 .fingerprint_of(&DepNode::new_no_params(DepKind::Krate));
714 let link_meta = link::build_link_meta(crate_hash);
715 let exported_symbol_node_ids = find_exported_symbols(tcx);
717 let shared_ccx = SharedCrateContext::new(tcx);
718 // Translate the metadata.
719 let llmod_id = "metadata";
720 let (metadata_llcx, metadata_llmod, metadata) =
721 time(tcx.sess.time_passes(), "write metadata", || {
722 write_metadata(tcx, llmod_id, &link_meta, &exported_symbol_node_ids)
725 let metadata_module = ModuleTranslation {
726 name: link::METADATA_MODULE_NAME.to_string(),
727 llmod_id: llmod_id.to_string(),
728 source: ModuleSource::Translated(ModuleLlvm {
730 llmod: metadata_llmod,
731 tm: create_target_machine(tcx.sess),
733 kind: ModuleKind::Metadata,
736 let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
737 Some(time_graph::TimeGraph::new())
742 // Skip crate items and just output metadata in -Z no-trans mode.
743 if tcx.sess.opts.debugging_opts.no_trans ||
744 !tcx.sess.opts.output_types.should_trans() {
745 let ongoing_translation = write::start_async_translation(
753 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
754 ongoing_translation.translation_finished(tcx);
756 assert_and_save_dep_graph(tcx);
758 ongoing_translation.check_for_errors(tcx.sess);
760 return ongoing_translation;
763 // Run the translation item collector and partition the collected items into
766 shared_ccx.tcx().collect_and_partition_translation_items(LOCAL_CRATE).1;
767 let codegen_units = (*codegen_units).clone();
769 // Force all codegen_unit queries so they are already either red or green
770 // when compile_codegen_unit accesses them. We are not able to re-execute
771 // the codegen_unit query from just the DepNode, so an unknown color would
772 // lead to having to re-execute compile_codegen_unit, possibly
774 if tcx.dep_graph.is_fully_enabled() {
775 for cgu in &codegen_units {
776 tcx.codegen_unit(cgu.name().clone());
780 let ongoing_translation = write::start_async_translation(
786 codegen_units.len());
788 // Translate an allocator shim, if any
789 let allocator_module = if let Some(kind) = tcx.sess.allocator_kind.get() {
791 let llmod_id = "allocator";
793 context::create_context_and_module(tcx.sess, llmod_id);
794 let modules = ModuleLlvm {
797 tm: create_target_machine(tcx.sess),
799 time(tcx.sess.time_passes(), "write allocator module", || {
800 allocator::trans(tcx, &modules, kind)
803 Some(ModuleTranslation {
804 name: link::ALLOCATOR_MODULE_NAME.to_string(),
805 llmod_id: llmod_id.to_string(),
806 source: ModuleSource::Translated(modules),
807 kind: ModuleKind::Allocator,
814 if let Some(allocator_module) = allocator_module {
815 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, allocator_module);
818 ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
820 // We sort the codegen units by size. This way we can schedule work for LLVM
821 // a bit more efficiently. Note that "size" is defined rather crudely at the
822 // moment as it is just the number of TransItems in the CGU, not taking into
823 // account the size of each TransItem.
824 let codegen_units = {
825 let mut codegen_units = codegen_units;
826 codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
830 let mut total_trans_time = Duration::new(0, 0);
831 let mut all_stats = Stats::default();
833 for cgu in codegen_units.into_iter() {
834 ongoing_translation.wait_for_signal_to_translate_item();
835 ongoing_translation.check_for_errors(tcx.sess);
837 // First, if incremental compilation is enabled, we try to re-use the
838 // codegen unit from the cache.
839 if tcx.dep_graph.is_fully_enabled() {
840 let cgu_id = cgu.work_product_id();
842 // Check whether there is a previous work-product we can
843 // re-use. Not only must the file exist, and the inputs not
844 // be dirty, but the hash of the symbols we will generate must
846 if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
847 let dep_node = &DepNode::new(tcx,
848 DepConstructor::CompileCodegenUnit(cgu.name().clone()));
850 // We try to mark the DepNode::CompileCodegenUnit green. If we
851 // succeed it means that none of the dependencies has changed
852 // and we can safely re-use.
853 if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
854 // Append ".rs" to LLVM module identifier.
856 // LLVM code generator emits a ".file filename" directive
857 // for ELF backends. Value of the "filename" is set as the
858 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
859 // crashes if the module identifier is same as other symbols
860 // such as a function name in the module.
861 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
862 let llmod_id = format!("{}.rs", cgu.name());
864 let module = ModuleTranslation {
865 name: cgu.name().to_string(),
866 source: ModuleSource::Preexisting(buf),
867 kind: ModuleKind::Regular,
870 tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
871 write::submit_translated_module_to_llvm(tcx, module, 0);
872 // Continue to next cgu, this one is done.
876 // This can happen if files were deleted from the cache
877 // directory for some reason. We just re-compile then.
881 let _timing_guard = time_graph.as_ref().map(|time_graph| {
882 time_graph.start(write::TRANS_WORKER_TIMELINE,
883 write::TRANS_WORK_PACKAGE_KIND,
884 &format!("codegen {}", cgu.name()))
886 let start_time = Instant::now();
887 all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
888 total_trans_time += start_time.elapsed();
889 ongoing_translation.check_for_errors(tcx.sess);
892 ongoing_translation.translation_finished(tcx);
894 // Since the main thread is sometimes blocked during trans, we keep track
895 // -Ztime-passes output manually.
896 print_time_passes_entry(tcx.sess.time_passes(),
897 "translate to LLVM IR",
900 if tcx.sess.opts.incremental.is_some() {
901 assert_module_sources::assert_module_sources(tcx);
904 symbol_names_test::report_symbol_names(tcx);
906 if shared_ccx.sess().trans_stats() {
907 println!("--- trans stats ---");
908 println!("n_glues_created: {}", all_stats.n_glues_created);
909 println!("n_null_glues: {}", all_stats.n_null_glues);
910 println!("n_real_glues: {}", all_stats.n_real_glues);
912 println!("n_fns: {}", all_stats.n_fns);
913 println!("n_inlines: {}", all_stats.n_inlines);
914 println!("n_closures: {}", all_stats.n_closures);
915 println!("fn stats:");
916 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
917 for &(ref name, insns) in all_stats.fn_stats.iter() {
918 println!("{} insns, {}", insns, *name);
922 if shared_ccx.sess().count_llvm_insns() {
923 for (k, v) in all_stats.llvm_insns.iter() {
924 println!("{:7} {}", *v, *k);
928 ongoing_translation.check_for_errors(tcx.sess);
930 assert_and_save_dep_graph(tcx);
934 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
935 time(tcx.sess.time_passes(),
937 || rustc_incremental::assert_dep_graph(tcx));
939 time(tcx.sess.time_passes(),
940 "serialize dep graph",
941 || rustc_incremental::save_dep_graph(tcx));
944 #[inline(never)] // give this a place in the profiler
945 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
946 where I: Iterator<Item=&'a MonoItem<'tcx>>
948 let mut symbols: Vec<_> = trans_items.map(|trans_item| {
949 (trans_item, trans_item.symbol_name(tcx))
952 (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
956 for pair in (&symbols[..]).windows(2) {
957 let sym1 = &pair[0].1;
958 let sym2 = &pair[1].1;
961 let trans_item1 = pair[0].0;
962 let trans_item2 = pair[1].0;
964 let span1 = trans_item1.local_span(tcx);
965 let span2 = trans_item2.local_span(tcx);
967 // Deterministically select one of the spans for error reporting
968 let span = match (span1, span2) {
969 (Some(span1), Some(span2)) => {
970 Some(if span1.lo().0 > span2.lo().0 {
977 (None, Some(span)) => Some(span),
981 let error_message = format!("symbol `{}` is already defined", sym1);
983 if let Some(span) = span {
984 tcx.sess.span_fatal(span, &error_message)
986 tcx.sess.fatal(&error_message)
992 fn collect_and_partition_translation_items<'a, 'tcx>(
993 tcx: TyCtxt<'a, 'tcx, 'tcx>,
995 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
997 assert_eq!(cnum, LOCAL_CRATE);
998 let time_passes = tcx.sess.time_passes();
1000 let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
1002 let mode_string = s.to_lowercase();
1003 let mode_string = mode_string.trim();
1004 if mode_string == "eager" {
1005 MonoItemCollectionMode::Eager
1007 if mode_string != "lazy" {
1008 let message = format!("Unknown codegen-item collection mode '{}'. \
1009 Falling back to 'lazy' mode.",
1011 tcx.sess.warn(&message);
1014 MonoItemCollectionMode::Lazy
1017 None => MonoItemCollectionMode::Lazy
1020 let (items, inlining_map) =
1021 time(time_passes, "translation item collection", || {
1022 collector::collect_crate_mono_items(tcx, collection_mode)
1025 assert_symbols_are_distinct(tcx, items.iter());
1027 let strategy = if tcx.sess.opts.incremental.is_some() {
1028 PartitioningStrategy::PerModule
1030 PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
1033 let codegen_units = time(time_passes, "codegen unit partitioning", || {
1034 partitioning::partition(tcx,
1035 items.iter().cloned(),
1040 .collect::<Vec<_>>()
1043 let translation_items: DefIdSet = items.iter().filter_map(|trans_item| {
1045 MonoItem::Fn(ref instance) => Some(instance.def_id()),
1050 if tcx.sess.opts.debugging_opts.print_trans_items.is_some() {
1051 let mut item_to_cgus = FxHashMap();
1053 for cgu in &codegen_units {
1054 for (&trans_item, &linkage) in cgu.items() {
1055 item_to_cgus.entry(trans_item)
1056 .or_insert(Vec::new())
1057 .push((cgu.name().clone(), linkage));
1061 let mut item_keys: Vec<_> = items
1064 let mut output = i.to_string(tcx);
1065 output.push_str(" @@");
1066 let mut empty = Vec::new();
1067 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1068 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1070 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1071 output.push_str(" ");
1072 output.push_str(&cgu_name);
1074 let linkage_abbrev = match linkage {
1075 Linkage::External => "External",
1076 Linkage::AvailableExternally => "Available",
1077 Linkage::LinkOnceAny => "OnceAny",
1078 Linkage::LinkOnceODR => "OnceODR",
1079 Linkage::WeakAny => "WeakAny",
1080 Linkage::WeakODR => "WeakODR",
1081 Linkage::Appending => "Appending",
1082 Linkage::Internal => "Internal",
1083 Linkage::Private => "Private",
1084 Linkage::ExternalWeak => "ExternalWeak",
1085 Linkage::Common => "Common",
1088 output.push_str("[");
1089 output.push_str(linkage_abbrev);
1090 output.push_str("]");
1098 for item in item_keys {
1099 println!("TRANS_ITEM {}", item);
1103 (Arc::new(translation_items), Arc::new(codegen_units))
1107 pub fn new(tcx: TyCtxt) -> CrateInfo {
1108 let mut info = CrateInfo {
1109 panic_runtime: None,
1110 compiler_builtins: None,
1111 profiler_runtime: None,
1112 sanitizer_runtime: None,
1113 is_no_builtins: FxHashSet(),
1114 native_libraries: FxHashMap(),
1115 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1116 link_args: tcx.link_args(LOCAL_CRATE),
1117 crate_name: FxHashMap(),
1118 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1119 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1120 used_crate_source: FxHashMap(),
1123 for &cnum in tcx.crates().iter() {
1124 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1125 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1126 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1127 if tcx.is_panic_runtime(cnum) {
1128 info.panic_runtime = Some(cnum);
1130 if tcx.is_compiler_builtins(cnum) {
1131 info.compiler_builtins = Some(cnum);
1133 if tcx.is_profiler_runtime(cnum) {
1134 info.profiler_runtime = Some(cnum);
1136 if tcx.is_sanitizer_runtime(cnum) {
1137 info.sanitizer_runtime = Some(cnum);
1139 if tcx.is_no_builtins(cnum) {
1140 info.is_no_builtins.insert(cnum);
1149 fn is_translated_function(tcx: TyCtxt, id: DefId) -> bool {
1150 let (all_trans_items, _) =
1151 tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1152 all_trans_items.contains(&id)
1155 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1156 cgu: InternedString) -> Stats {
1157 let cgu = tcx.codegen_unit(cgu);
1159 let start_time = Instant::now();
1160 let (stats, module) = module_translation(tcx, cgu);
1161 let time_to_translate = start_time.elapsed();
1163 // We assume that the cost to run LLVM on a CGU is proportional to
1164 // the time we needed for translating it.
1165 let cost = time_to_translate.as_secs() * 1_000_000_000 +
1166 time_to_translate.subsec_nanos() as u64;
1168 write::submit_translated_module_to_llvm(tcx,
1173 fn module_translation<'a, 'tcx>(
1174 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1175 cgu: Arc<CodegenUnit<'tcx>>)
1176 -> (Stats, ModuleTranslation)
1178 let cgu_name = cgu.name().to_string();
1180 // Append ".rs" to LLVM module identifier.
1182 // LLVM code generator emits a ".file filename" directive
1183 // for ELF backends. Value of the "filename" is set as the
1184 // LLVM module identifier. Due to a LLVM MC bug[1], LLVM
1185 // crashes if the module identifier is same as other symbols
1186 // such as a function name in the module.
1187 // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
1188 let llmod_id = format!("{}-{}.rs",
1190 tcx.crate_disambiguator(LOCAL_CRATE)
1191 .to_fingerprint().to_hex());
1193 // Instantiate translation items without filling out definitions yet...
1194 let scx = SharedCrateContext::new(tcx);
1195 let lcx = LocalCrateContext::new(&scx, cgu, &llmod_id);
1197 let ccx = CrateContext::new(&scx, &lcx);
1198 let trans_items = ccx.codegen_unit()
1199 .items_in_deterministic_order(ccx.tcx());
1200 for &(trans_item, (linkage, visibility)) in &trans_items {
1201 trans_item.predefine(&ccx, linkage, visibility);
1204 // ... and now that we have everything pre-defined, fill out those definitions.
1205 for &(trans_item, _) in &trans_items {
1206 trans_item.define(&ccx);
1209 // If this codegen unit contains the main function, also create the
1211 maybe_create_entry_wrapper(&ccx);
1213 // Run replace-all-uses-with for statics that need it
1214 for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1216 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1217 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1218 llvm::LLVMDeleteGlobal(old_g);
1222 // Create the llvm.used variable
1223 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1224 if !ccx.used_statics().borrow().is_empty() {
1225 let name = CString::new("llvm.used").unwrap();
1226 let section = CString::new("llvm.metadata").unwrap();
1227 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1230 let g = llvm::LLVMAddGlobal(ccx.llmod(),
1231 val_ty(array).to_ref(),
1233 llvm::LLVMSetInitializer(g, array);
1234 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1235 llvm::LLVMSetSection(g, section.as_ptr());
1239 // Finalize debuginfo
1240 if ccx.sess().opts.debuginfo != NoDebugInfo {
1241 debuginfo::finalize(&ccx);
1244 let llvm_module = ModuleLlvm {
1247 tm: create_target_machine(ccx.sess()),
1252 source: ModuleSource::Translated(llvm_module),
1253 kind: ModuleKind::Regular,
1258 (lcx.into_stats(), module)
1262 pub fn provide(providers: &mut Providers) {
1263 providers.collect_and_partition_translation_items =
1264 collect_and_partition_translation_items;
1266 providers.is_translated_function = is_translated_function;
1268 providers.codegen_unit = |tcx, name| {
1269 let (_, all) = tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1271 .find(|cgu| *cgu.name() == name)
1273 .expect(&format!("failed to find cgu with name {:?}", name))
1275 providers.compile_codegen_unit = compile_codegen_unit;
1278 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1280 Linkage::External => llvm::Linkage::ExternalLinkage,
1281 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1282 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1283 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1284 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1285 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1286 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1287 Linkage::Internal => llvm::Linkage::InternalLinkage,
1288 Linkage::Private => llvm::Linkage::PrivateLinkage,
1289 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1290 Linkage::Common => llvm::Linkage::CommonLinkage,
1294 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1296 Visibility::Default => llvm::Visibility::Default,
1297 Visibility::Hidden => llvm::Visibility::Hidden,
1298 Visibility::Protected => llvm::Visibility::Protected,
1302 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1303 // the HashStable trait. Normally DepGraph::with_task() calls are
1304 // hidden behind queries, but CGU creation is a special case in two
1305 // ways: (1) it's not a query and (2) CGU are output nodes, so their
1306 // Fingerprints are not actually needed. It remains to be clarified
1307 // how exactly this case will be handled in the red/green system but
1308 // for now we content ourselves with providing a no-op HashStable
1309 // implementation for CGUs.
1310 mod temp_stable_hash_impls {
1311 use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1313 use ModuleTranslation;
1315 impl<HCX> HashStable<HCX> for ModuleTranslation {
1316 fn hash_stable<W: StableHasherResult>(&self,
1318 _: &mut StableHasher<W>) {