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 //! Codegen the completed AST to the LLVM IR.
13 //! Some functions here, such as codegen_block and codegen_expr, return a value --
14 //! the result of the codegen to LLVM -- while others, such as codegen_fn
15 //! and mono_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 codegen:
20 //! * There's no way to find out the Ty type of a Value. Doing so
21 //! would be "trying to get the eggs out of an omelette" (credit:
22 //! pcwalton). You can, instead, find out its llvm::Type by calling val_ty,
23 //! but one llvm::Type corresponds to many `Ty`s; for instance, tup(int, int,
24 //! int) and rec(x=int, y=int, z=int) will have the same llvm::Type.
26 use super::ModuleLlvm;
27 use super::ModuleCodegen;
28 use super::ModuleKind;
29 use super::CachedModuleCodegen;
32 use back::write::{self, OngoingCodegen};
33 use llvm::{self, TypeKind, get_param};
35 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
36 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
37 use rustc::middle::lang_items::StartFnLangItem;
38 use rustc::middle::weak_lang_items;
39 use rustc::mir::mono::{Linkage, Visibility, Stats, CodegenUnitNameBuilder};
40 use rustc::middle::cstore::{EncodedMetadata};
41 use rustc::ty::{self, Ty, TyCtxt};
42 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, VariantIdx};
43 use rustc::ty::query::Providers;
44 use rustc::middle::cstore::{self, LinkagePreference};
45 use rustc::middle::exported_symbols;
46 use rustc::util::common::{time, print_time_passes_entry};
47 use rustc::util::profiling::ProfileCategory;
48 use rustc::session::config::{self, DebugInfo, EntryFnType, Lto};
49 use rustc::session::Session;
50 use rustc_incremental;
52 use mir::place::PlaceRef;
54 use builder::{Builder, MemFlags};
56 use common::{C_bool, C_bytes_in_context, C_usize};
57 use rustc_mir::monomorphize::item::DefPathBasedNames;
58 use common::{C_struct_in_context, C_array, val_ty};
60 use context::CodegenCx;
65 use monomorphize::Instance;
66 use monomorphize::partitioning::{CodegenUnit, CodegenUnitExt};
67 use rustc_codegen_utils::symbol_names_test;
69 use mono_item::{MonoItem, MonoItemExt};
71 use type_of::LayoutLlvmExt;
72 use rustc::util::nodemap::FxHashMap;
74 use rustc_data_structures::small_c_str::SmallCStr;
75 use rustc_data_structures::sync::Lrc;
76 use rustc_data_structures::indexed_vec::Idx;
80 use std::ffi::CString;
81 use std::ops::{Deref, DerefMut};
83 use std::time::{Instant, Duration};
85 use syntax_pos::symbol::InternedString;
87 use rustc::hir::{self, CodegenFnAttrs};
91 use mir::operand::OperandValue;
93 use rustc_codegen_utils::check_for_rustc_errors_attr;
95 pub struct StatRecorder<'a, 'll: 'a, 'tcx: 'll> {
96 cx: &'a CodegenCx<'ll, 'tcx>,
101 impl StatRecorder<'a, 'll, 'tcx> {
102 pub fn new(cx: &'a CodegenCx<'ll, 'tcx>, name: String) -> Self {
103 let istart = cx.stats.borrow().n_llvm_insns;
112 impl Drop for StatRecorder<'a, 'll, 'tcx> {
114 if self.cx.sess().codegen_stats() {
115 let mut stats = self.cx.stats.borrow_mut();
116 let iend = stats.n_llvm_insns;
117 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
119 // Reset LLVM insn count to avoid compound costs.
120 stats.n_llvm_insns = self.istart;
125 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
127 -> llvm::IntPredicate {
129 hir::BinOpKind::Eq => llvm::IntEQ,
130 hir::BinOpKind::Ne => llvm::IntNE,
131 hir::BinOpKind::Lt => if signed { llvm::IntSLT } else { llvm::IntULT },
132 hir::BinOpKind::Le => if signed { llvm::IntSLE } else { llvm::IntULE },
133 hir::BinOpKind::Gt => if signed { llvm::IntSGT } else { llvm::IntUGT },
134 hir::BinOpKind::Ge => if signed { llvm::IntSGE } else { llvm::IntUGE },
136 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
143 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> llvm::RealPredicate {
145 hir::BinOpKind::Eq => llvm::RealOEQ,
146 hir::BinOpKind::Ne => llvm::RealUNE,
147 hir::BinOpKind::Lt => llvm::RealOLT,
148 hir::BinOpKind::Le => llvm::RealOLE,
149 hir::BinOpKind::Gt => llvm::RealOGT,
150 hir::BinOpKind::Ge => llvm::RealOGE,
152 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
159 pub fn compare_simd_types(
160 bx: &Builder<'a, 'll, 'tcx>,
167 let signed = match t.sty {
169 let cmp = bin_op_to_fcmp_predicate(op);
170 return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
172 ty::Uint(_) => false,
174 _ => bug!("compare_simd_types: invalid SIMD type"),
177 let cmp = bin_op_to_icmp_predicate(op, signed);
178 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
179 // to get the correctly sized type. This will compile to a single instruction
180 // once the IR is converted to assembly if the SIMD instruction is supported
181 // by the target architecture.
182 bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
185 /// Retrieve the information we are losing (making dynamic) in an unsizing
188 /// The `old_info` argument is a bit funny. It is intended for use
189 /// in an upcast, where the new vtable for an object will be derived
190 /// from the old one.
192 cx: &CodegenCx<'ll, 'tcx>,
195 old_info: Option<&'ll Value>,
197 let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
198 match (&source.sty, &target.sty) {
199 (&ty::Array(_, len), &ty::Slice(_)) => {
200 C_usize(cx, len.unwrap_usize(cx.tcx))
202 (&ty::Dynamic(..), &ty::Dynamic(..)) => {
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::Dynamic(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(
222 bx: &Builder<'a, 'll, 'tcx>,
226 ) -> (&'ll Value, &'ll Value) {
227 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
228 match (&src_ty.sty, &dst_ty.sty) {
232 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
233 (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
234 &ty::RawPtr(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::Adt(def_a, _), &ty::Adt(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::Adt(def_a, _), &ty::Adt(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, true)),
268 bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1, true)))
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(
277 bx: &Builder<'a, 'll, 'tcx>,
278 src: PlaceRef<'ll, 'tcx>,
279 dst: PlaceRef<'ll, 'tcx>
281 let src_ty = src.layout.ty;
282 let dst_ty = dst.layout.ty;
283 let coerce_ptr = || {
284 let (base, info) = match src.load(bx).val {
285 OperandValue::Pair(base, info) => {
286 // fat-ptr to fat-ptr unsize preserves the vtable
287 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
288 // So we need to pointercast the base to ensure
289 // the types match up.
290 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
291 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
293 OperandValue::Immediate(base) => {
294 unsize_thin_ptr(bx, base, src_ty, dst_ty)
296 OperandValue::Ref(..) => bug!()
298 OperandValue::Pair(base, info).store(bx, dst);
300 match (&src_ty.sty, &dst_ty.sty) {
301 (&ty::Ref(..), &ty::Ref(..)) |
302 (&ty::Ref(..), &ty::RawPtr(..)) |
303 (&ty::RawPtr(..), &ty::RawPtr(..)) => {
306 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
310 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
311 assert_eq!(def_a, def_b);
313 for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
314 let src_f = src.project_field(bx, i);
315 let dst_f = dst.project_field(bx, i);
317 if dst_f.layout.is_zst() {
321 if src_f.layout.ty == dst_f.layout.ty {
322 memcpy_ty(bx, dst_f.llval, dst_f.align, src_f.llval, src_f.align,
323 src_f.layout, MemFlags::empty());
325 coerce_unsized_into(bx, src_f, dst_f);
329 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
335 pub fn cast_shift_expr_rhs(
336 cx: &Builder<'_, 'll, '_>, op: hir::BinOpKind, lhs: &'ll Value, rhs: &'ll Value
338 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
341 fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
347 where F: FnOnce(&'ll Value, &'ll Type) -> &'ll Value,
348 G: FnOnce(&'ll Value, &'ll Type) -> &'ll Value
350 // Shifts may have any size int on the rhs
352 let mut rhs_llty = val_ty(rhs);
353 let mut lhs_llty = val_ty(lhs);
354 if rhs_llty.kind() == TypeKind::Vector {
355 rhs_llty = rhs_llty.element_type()
357 if lhs_llty.kind() == TypeKind::Vector {
358 lhs_llty = lhs_llty.element_type()
360 let rhs_sz = rhs_llty.int_width();
361 let lhs_sz = lhs_llty.int_width();
364 } else if lhs_sz > rhs_sz {
365 // FIXME (#1877: If in the future shifting by negative
366 // values is no longer undefined then this is wrong.
376 /// Returns whether this session's target will use SEH-based unwinding.
378 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
379 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
380 /// 64-bit MinGW) instead of "full SEH".
381 pub fn wants_msvc_seh(sess: &Session) -> bool {
382 sess.target.target.options.is_like_msvc
385 pub fn call_assume(bx: &Builder<'_, 'll, '_>, val: &'ll Value) {
386 let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
387 bx.call(assume_intrinsic, &[val], None);
390 pub fn from_immediate(bx: &Builder<'_, 'll, '_>, val: &'ll Value) -> &'ll Value {
391 if val_ty(val) == Type::i1(bx.cx) {
392 bx.zext(val, Type::i8(bx.cx))
399 bx: &Builder<'_, 'll, '_>,
401 layout: layout::TyLayout,
403 if let layout::Abi::Scalar(ref scalar) = layout.abi {
404 return to_immediate_scalar(bx, val, scalar);
409 pub fn to_immediate_scalar(
410 bx: &Builder<'_, 'll, '_>,
412 scalar: &layout::Scalar,
414 if scalar.is_bool() {
415 return bx.trunc(val, Type::i1(bx.cx));
421 bx: &Builder<'_, 'll, '_>,
429 if flags.contains(MemFlags::NONTEMPORAL) {
430 // HACK(nox): This is inefficient but there is no nontemporal memcpy.
431 let val = bx.load(src, src_align);
432 let ptr = bx.pointercast(dst, val_ty(val).ptr_to());
433 bx.store_with_flags(val, ptr, dst_align, flags);
437 let src_ptr = bx.pointercast(src, Type::i8p(cx));
438 let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
439 let size = bx.intcast(n_bytes, cx.isize_ty, false);
440 let volatile = flags.contains(MemFlags::VOLATILE);
441 bx.memcpy(dst_ptr, dst_align.abi(), src_ptr, src_align.abi(), size, volatile);
445 bx: &Builder<'_, 'll, 'tcx>,
450 layout: TyLayout<'tcx>,
453 let size = layout.size.bytes();
458 call_memcpy(bx, dst, dst_align, src, src_align, C_usize(bx.cx, size), flags);
462 bx: &Builder<'_, 'll, '_>,
464 fill_byte: &'ll Value,
469 let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
470 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
471 let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
472 let volatile = C_bool(bx.cx, volatile);
473 bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
476 pub fn codegen_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
477 let _s = if cx.sess().codegen_stats() {
478 let mut instance_name = String::new();
479 DefPathBasedNames::new(cx.tcx, true, true)
480 .push_def_path(instance.def_id(), &mut instance_name);
481 Some(StatRecorder::new(cx, instance_name))
486 // this is an info! to allow collecting monomorphization statistics
487 // and to allow finding the last function before LLVM aborts from
489 info!("codegen_instance({})", instance);
491 let sig = instance.fn_sig(cx.tcx);
492 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
494 let lldecl = cx.instances.borrow().get(&instance).cloned().unwrap_or_else(||
495 bug!("Instance `{:?}` not already declared", instance));
497 cx.stats.borrow_mut().n_closures += 1;
499 let mir = cx.tcx.instance_mir(instance.def);
500 mir::codegen_mir(cx, lldecl, &mir, instance, sig);
503 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
504 let sect = match attrs.link_section {
509 let buf = SmallCStr::new(§.as_str());
510 llvm::LLVMSetSection(llval, buf.as_ptr());
514 /// Create the `main` function which will initialize the rust runtime and call
515 /// users main function.
516 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
517 let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
518 Some((id, span, _)) => {
519 (cx.tcx.hir.local_def_id(id), span)
524 let instance = Instance::mono(cx.tcx, main_def_id);
526 if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
527 // We want to create the wrapper in the same codegen unit as Rust's main
532 let main_llfn = callee::get_fn(cx, instance);
534 let et = cx.sess().entry_fn.get().map(|e| e.2);
536 Some(EntryFnType::Main) => create_entry_fn(cx, span, main_llfn, main_def_id, true),
537 Some(EntryFnType::Start) => create_entry_fn(cx, span, main_llfn, main_def_id, false),
538 None => {} // Do nothing.
542 cx: &CodegenCx<'ll, '_>,
544 rust_main: &'ll Value,
545 rust_main_def_id: DefId,
546 use_start_lang_item: bool,
548 let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], Type::c_int(cx));
550 let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
551 // Given that `main()` has no arguments,
552 // then its return type cannot have
553 // late-bound regions, since late-bound
554 // regions must appear in the argument
556 let main_ret_ty = cx.tcx.erase_regions(
557 &main_ret_ty.no_bound_vars().unwrap(),
560 if declare::get_defined_value(cx, "main").is_some() {
561 // FIXME: We should be smart and show a better diagnostic here.
562 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
563 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
565 cx.sess().abort_if_errors();
568 let llfn = declare::declare_cfn(cx, "main", llfty);
570 // `main` should respect same config for frame pointer elimination as rest of code
571 attributes::set_frame_pointer_elimination(cx, llfn);
572 attributes::apply_target_cpu_attr(cx, llfn);
574 let bx = Builder::new_block(cx, llfn, "top");
576 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
578 // Params from native main() used as args for rust start function
579 let param_argc = get_param(llfn, 0);
580 let param_argv = get_param(llfn, 1);
581 let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
582 let arg_argv = param_argv;
584 let (start_fn, args) = if use_start_lang_item {
585 let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
586 let start_fn = callee::resolve_and_get_fn(
589 cx.tcx.intern_substs(&[main_ret_ty.into()]),
591 (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
594 debug!("using user-defined start fn");
595 (rust_main, vec![arg_argc, arg_argv])
598 let result = bx.call(start_fn, &args, None);
599 bx.ret(bx.intcast(result, Type::c_int(cx), true));
603 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
604 llvm_module: &ModuleLlvm)
607 use flate2::Compression;
608 use flate2::write::DeflateEncoder;
610 let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
612 #[derive(PartialEq, Eq, PartialOrd, Ord)]
619 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
621 config::CrateType::Executable |
622 config::CrateType::Staticlib |
623 config::CrateType::Cdylib => MetadataKind::None,
625 config::CrateType::Rlib => MetadataKind::Uncompressed,
627 config::CrateType::Dylib |
628 config::CrateType::ProcMacro => MetadataKind::Compressed,
630 }).max().unwrap_or(MetadataKind::None);
632 if kind == MetadataKind::None {
633 return EncodedMetadata::new();
636 let metadata = tcx.encode_metadata();
637 if kind == MetadataKind::Uncompressed {
641 assert!(kind == MetadataKind::Compressed);
642 let mut compressed = tcx.metadata_encoding_version();
643 DeflateEncoder::new(&mut compressed, Compression::fast())
644 .write_all(&metadata.raw_data).unwrap();
646 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
647 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
648 let name = exported_symbols::metadata_symbol_name(tcx);
649 let buf = CString::new(name).unwrap();
650 let llglobal = unsafe {
651 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst), buf.as_ptr())
654 llvm::LLVMSetInitializer(llglobal, llconst);
655 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
656 let name = SmallCStr::new(section_name);
657 llvm::LLVMSetSection(llglobal, name.as_ptr());
659 // Also generate a .section directive to force no
660 // flags, at least for ELF outputs, so that the
661 // metadata doesn't get loaded into memory.
662 let directive = format!(".section {}", section_name);
663 let directive = CString::new(directive).unwrap();
664 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
669 pub struct ValueIter<'ll> {
670 cur: Option<&'ll Value>,
671 step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
674 impl Iterator for ValueIter<'ll> {
675 type Item = &'ll Value;
677 fn next(&mut self) -> Option<&'ll Value> {
679 if let Some(old) = old {
680 self.cur = unsafe { (self.step)(old) };
686 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
689 cur: llvm::LLVMGetFirstGlobal(llmod),
690 step: llvm::LLVMGetNextGlobal,
695 fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
696 cgu: &CodegenUnit<'tcx>)
698 if !tcx.dep_graph.is_fully_enabled() {
702 let work_product_id = &cgu.work_product_id();
703 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
704 // We don't have anything cached for this CGU. This can happen
705 // if the CGU did not exist in the previous session.
709 // Try to mark the CGU as green. If it we can do so, it means that nothing
710 // affecting the LLVM module has changed and we can re-use a cached version.
711 // If we compile with any kind of LTO, this means we can re-use the bitcode
712 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
713 // know that later). If we are not doing LTO, there is only one optimized
714 // version of each module, so we re-use that.
715 let dep_node = cgu.codegen_dep_node(tcx);
716 assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
717 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
720 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
721 // We can re-use either the pre- or the post-thinlto state
722 if tcx.sess.lto() != Lto::No {
732 pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
733 rx: mpsc::Receiver<Box<dyn Any + Send>>)
736 check_for_rustc_errors_attr(tcx);
738 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
740 // Codegen the metadata.
741 tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
743 let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
745 Some("metadata")).as_str()
747 let metadata_llvm_module = ModuleLlvm::new(tcx.sess, &metadata_cgu_name);
748 let metadata = time(tcx.sess, "write metadata", || {
749 write_metadata(tcx, &metadata_llvm_module)
751 tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
753 let metadata_module = ModuleCodegen {
754 name: metadata_cgu_name,
755 module_llvm: metadata_llvm_module,
756 kind: ModuleKind::Metadata,
759 let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
760 Some(time_graph::TimeGraph::new())
765 // Skip crate items and just output metadata in -Z no-codegen mode.
766 if tcx.sess.opts.debugging_opts.no_codegen ||
767 !tcx.sess.opts.output_types.should_codegen() {
768 let ongoing_codegen = write::start_async_codegen(
775 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
776 ongoing_codegen.codegen_finished(tcx);
778 assert_and_save_dep_graph(tcx);
780 ongoing_codegen.check_for_errors(tcx.sess);
782 return ongoing_codegen;
785 // Run the monomorphization collector and partition the collected items into
787 let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
788 let codegen_units = (*codegen_units).clone();
790 // Force all codegen_unit queries so they are already either red or green
791 // when compile_codegen_unit accesses them. We are not able to re-execute
792 // the codegen_unit query from just the DepNode, so an unknown color would
793 // lead to having to re-execute compile_codegen_unit, possibly
795 if tcx.dep_graph.is_fully_enabled() {
796 for cgu in &codegen_units {
797 tcx.codegen_unit(cgu.name().clone());
801 let ongoing_codegen = write::start_async_codegen(
806 codegen_units.len());
807 let ongoing_codegen = AbortCodegenOnDrop(Some(ongoing_codegen));
809 // Codegen an allocator shim, if necessary.
811 // If the crate doesn't have an `allocator_kind` set then there's definitely
812 // no shim to generate. Otherwise we also check our dependency graph for all
813 // our output crate types. If anything there looks like its a `Dynamic`
814 // linkage, then it's already got an allocator shim and we'll be using that
815 // one instead. If nothing exists then it's our job to generate the
817 let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
820 use rustc::middle::dependency_format::Linkage;
821 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
823 let allocator_module = if any_dynamic_crate {
825 } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
826 let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
828 Some("allocator")).as_str()
830 let modules = ModuleLlvm::new(tcx.sess, &llmod_id);
831 time(tcx.sess, "write allocator module", || {
833 allocator::codegen(tcx, &modules, kind)
839 module_llvm: modules,
840 kind: ModuleKind::Allocator,
846 if let Some(allocator_module) = allocator_module {
847 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
850 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
852 // We sort the codegen units by size. This way we can schedule work for LLVM
853 // a bit more efficiently.
854 let codegen_units = {
855 let mut codegen_units = codegen_units;
856 codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
860 let mut total_codegen_time = Duration::new(0, 0);
861 let mut all_stats = Stats::default();
863 for cgu in codegen_units.into_iter() {
864 ongoing_codegen.wait_for_signal_to_codegen_item();
865 ongoing_codegen.check_for_errors(tcx.sess);
867 let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
868 tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
872 let _timing_guard = time_graph.as_ref().map(|time_graph| {
873 time_graph.start(write::CODEGEN_WORKER_TIMELINE,
874 write::CODEGEN_WORK_PACKAGE_KIND,
875 &format!("codegen {}", cgu.name()))
877 let start_time = Instant::now();
878 let stats = compile_codegen_unit(tcx, *cgu.name());
879 all_stats.extend(stats);
880 total_codegen_time += start_time.elapsed();
883 CguReuse::PreLto => {
884 write::submit_pre_lto_module_to_llvm(tcx, CachedModuleCodegen {
885 name: cgu.name().to_string(),
886 source: cgu.work_product(tcx),
890 CguReuse::PostLto => {
891 write::submit_post_lto_module_to_llvm(tcx, CachedModuleCodegen {
892 name: cgu.name().to_string(),
893 source: cgu.work_product(tcx),
900 ongoing_codegen.codegen_finished(tcx);
902 // Since the main thread is sometimes blocked during codegen, we keep track
903 // -Ztime-passes output manually.
904 print_time_passes_entry(tcx.sess.time_passes(),
905 "codegen to LLVM IR",
908 rustc_incremental::assert_module_sources::assert_module_sources(tcx);
910 symbol_names_test::report_symbol_names(tcx);
912 if tcx.sess.codegen_stats() {
913 println!("--- codegen stats ---");
914 println!("n_glues_created: {}", all_stats.n_glues_created);
915 println!("n_null_glues: {}", all_stats.n_null_glues);
916 println!("n_real_glues: {}", all_stats.n_real_glues);
918 println!("n_fns: {}", all_stats.n_fns);
919 println!("n_inlines: {}", all_stats.n_inlines);
920 println!("n_closures: {}", all_stats.n_closures);
921 println!("fn stats:");
922 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
923 for &(ref name, insns) in all_stats.fn_stats.iter() {
924 println!("{} insns, {}", insns, *name);
928 if tcx.sess.count_llvm_insns() {
929 for (k, v) in all_stats.llvm_insns.iter() {
930 println!("{:7} {}", *v, *k);
934 ongoing_codegen.check_for_errors(tcx.sess);
936 assert_and_save_dep_graph(tcx);
937 ongoing_codegen.into_inner()
940 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
941 /// when it's dropped abnormally.
943 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
944 /// stumbled upon. The segfault was never reproduced locally, but it was
945 /// suspected to be releated to the fact that codegen worker threads were
946 /// sticking around by the time the main thread was exiting, causing issues.
948 /// This structure is an attempt to fix that issue where the `codegen_aborted`
949 /// message will block until all workers have finished. This should ensure that
950 /// even if the main codegen thread panics we'll wait for pending work to
951 /// complete before returning from the main thread, hopefully avoiding
954 /// If you see this comment in the code, then it means that this workaround
955 /// worked! We may yet one day track down the mysterious cause of that
957 struct AbortCodegenOnDrop(Option<OngoingCodegen>);
959 impl AbortCodegenOnDrop {
960 fn into_inner(mut self) -> OngoingCodegen {
961 self.0.take().unwrap()
965 impl Deref for AbortCodegenOnDrop {
966 type Target = OngoingCodegen;
968 fn deref(&self) -> &OngoingCodegen {
969 self.0.as_ref().unwrap()
973 impl DerefMut for AbortCodegenOnDrop {
974 fn deref_mut(&mut self) -> &mut OngoingCodegen {
975 self.0.as_mut().unwrap()
979 impl Drop for AbortCodegenOnDrop {
981 if let Some(codegen) = self.0.take() {
982 codegen.codegen_aborted();
987 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
990 || rustc_incremental::assert_dep_graph(tcx));
993 "serialize dep graph",
994 || rustc_incremental::save_dep_graph(tcx));
998 pub fn new(tcx: TyCtxt) -> CrateInfo {
999 let mut info = CrateInfo {
1000 panic_runtime: None,
1001 compiler_builtins: None,
1002 profiler_runtime: None,
1003 sanitizer_runtime: None,
1004 is_no_builtins: Default::default(),
1005 native_libraries: Default::default(),
1006 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1007 link_args: tcx.link_args(LOCAL_CRATE),
1008 crate_name: Default::default(),
1009 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1010 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1011 used_crate_source: Default::default(),
1012 wasm_imports: Default::default(),
1013 lang_item_to_crate: Default::default(),
1014 missing_lang_items: Default::default(),
1016 let lang_items = tcx.lang_items();
1018 let load_wasm_items = tcx.sess.crate_types.borrow()
1020 .any(|c| *c != config::CrateType::Rlib) &&
1021 tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
1023 if load_wasm_items {
1024 info.load_wasm_imports(tcx, LOCAL_CRATE);
1027 let crates = tcx.crates();
1029 let n_crates = crates.len();
1030 info.native_libraries.reserve(n_crates);
1031 info.crate_name.reserve(n_crates);
1032 info.used_crate_source.reserve(n_crates);
1033 info.missing_lang_items.reserve(n_crates);
1035 for &cnum in crates.iter() {
1036 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1037 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1038 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1039 if tcx.is_panic_runtime(cnum) {
1040 info.panic_runtime = Some(cnum);
1042 if tcx.is_compiler_builtins(cnum) {
1043 info.compiler_builtins = Some(cnum);
1045 if tcx.is_profiler_runtime(cnum) {
1046 info.profiler_runtime = Some(cnum);
1048 if tcx.is_sanitizer_runtime(cnum) {
1049 info.sanitizer_runtime = Some(cnum);
1051 if tcx.is_no_builtins(cnum) {
1052 info.is_no_builtins.insert(cnum);
1054 if load_wasm_items {
1055 info.load_wasm_imports(tcx, cnum);
1057 let missing = tcx.missing_lang_items(cnum);
1058 for &item in missing.iter() {
1059 if let Ok(id) = lang_items.require(item) {
1060 info.lang_item_to_crate.insert(item, id.krate);
1064 // No need to look for lang items that are whitelisted and don't
1065 // actually need to exist.
1066 let missing = missing.iter()
1068 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
1070 info.missing_lang_items.insert(cnum, missing);
1076 fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1077 self.wasm_imports.extend(tcx.wasm_import_module_map(cnum).iter().map(|(&id, module)| {
1078 let instance = Instance::mono(tcx, id);
1079 let import_name = tcx.symbol_name(instance);
1081 (import_name.to_string(), module.clone())
1086 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1087 cgu_name: InternedString)
1089 let start_time = Instant::now();
1091 let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
1092 let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
1096 let time_to_codegen = start_time.elapsed();
1098 // We assume that the cost to run LLVM on a CGU is proportional to
1099 // the time we needed for codegenning it.
1100 let cost = time_to_codegen.as_secs() * 1_000_000_000 +
1101 time_to_codegen.subsec_nanos() as u64;
1103 write::submit_codegened_module_to_llvm(tcx,
1108 fn module_codegen<'a, 'tcx>(
1109 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1110 cgu_name: InternedString)
1111 -> (Stats, ModuleCodegen)
1113 let cgu = tcx.codegen_unit(cgu_name);
1115 // Instantiate monomorphizations without filling out definitions yet...
1116 let llvm_module = ModuleLlvm::new(tcx.sess, &cgu_name.as_str());
1118 let cx = CodegenCx::new(tcx, cgu, &llvm_module);
1119 let mono_items = cx.codegen_unit
1120 .items_in_deterministic_order(cx.tcx);
1121 for &(mono_item, (linkage, visibility)) in &mono_items {
1122 mono_item.predefine(&cx, linkage, visibility);
1125 // ... and now that we have everything pre-defined, fill out those definitions.
1126 for &(mono_item, _) in &mono_items {
1127 mono_item.define(&cx);
1130 // If this codegen unit contains the main function, also create the
1132 maybe_create_entry_wrapper(&cx);
1134 // Run replace-all-uses-with for statics that need it
1135 for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1137 let bitcast = llvm::LLVMConstPointerCast(new_g, val_ty(old_g));
1138 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1139 llvm::LLVMDeleteGlobal(old_g);
1143 // Create the llvm.used variable
1144 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1145 if !cx.used_statics.borrow().is_empty() {
1146 let name = const_cstr!("llvm.used");
1147 let section = const_cstr!("llvm.metadata");
1148 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1151 let g = llvm::LLVMAddGlobal(cx.llmod,
1154 llvm::LLVMSetInitializer(g, array);
1155 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1156 llvm::LLVMSetSection(g, section.as_ptr());
1160 // Finalize debuginfo
1161 if cx.sess().opts.debuginfo != DebugInfo::None {
1162 debuginfo::finalize(&cx);
1165 cx.stats.into_inner()
1168 (stats, ModuleCodegen {
1169 name: cgu_name.to_string(),
1170 module_llvm: llvm_module,
1171 kind: ModuleKind::Regular,
1176 pub fn provide_both(providers: &mut Providers) {
1177 providers.dllimport_foreign_items = |tcx, krate| {
1178 let module_map = tcx.foreign_modules(krate);
1179 let module_map = module_map.iter()
1180 .map(|lib| (lib.def_id, lib))
1181 .collect::<FxHashMap<_, _>>();
1183 let dllimports = tcx.native_libraries(krate)
1186 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1189 let cfg = match lib.cfg {
1190 Some(ref cfg) => cfg,
1191 None => return true,
1193 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1195 .filter_map(|lib| lib.foreign_module)
1196 .map(|id| &module_map[&id])
1197 .flat_map(|module| module.foreign_items.iter().cloned())
1199 Lrc::new(dllimports)
1202 providers.is_dllimport_foreign_item = |tcx, def_id| {
1203 tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1207 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1209 Linkage::External => llvm::Linkage::ExternalLinkage,
1210 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1211 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1212 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1213 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1214 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1215 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1216 Linkage::Internal => llvm::Linkage::InternalLinkage,
1217 Linkage::Private => llvm::Linkage::PrivateLinkage,
1218 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1219 Linkage::Common => llvm::Linkage::CommonLinkage,
1223 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1225 Visibility::Default => llvm::Visibility::Default,
1226 Visibility::Hidden => llvm::Visibility::Hidden,
1227 Visibility::Protected => llvm::Visibility::Protected,
1231 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1232 // the HashStable trait. Normally DepGraph::with_task() calls are
1233 // hidden behind queries, but CGU creation is a special case in two
1234 // ways: (1) it's not a query and (2) CGU are output nodes, so their
1235 // Fingerprints are not actually needed. It remains to be clarified
1236 // how exactly this case will be handled in the red/green system but
1237 // for now we content ourselves with providing a no-op HashStable
1238 // implementation for CGUs.
1239 mod temp_stable_hash_impls {
1240 use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1244 impl<HCX> HashStable<HCX> for ModuleCodegen {
1245 fn hash_stable<W: StableHasherResult>(&self,
1247 _: &mut StableHasher<W>) {