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::ModuleSource;
28 use super::ModuleCodegen;
29 use super::ModuleKind;
33 use back::write::{self, OngoingCodegen};
34 use llvm::{self, TypeKind, get_param};
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};
43 use rustc::ty::query::Providers;
44 use rustc::dep_graph::{DepNode, DepConstructor};
45 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
46 use rustc::middle::exported_symbols;
47 use rustc::util::common::{time, print_time_passes_entry};
48 use rustc::util::profiling::ProfileCategory;
49 use rustc::session::config::{self, DebugInfo, EntryFnType};
50 use rustc::session::Session;
51 use rustc_incremental;
53 use mir::place::PlaceRef;
55 use builder::{Builder, MemFlags};
57 use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
58 use rustc_mir::monomorphize::collector::{self, MonoItemCollectionMode};
59 use rustc_mir::monomorphize::item::DefPathBasedNames;
60 use common::{self, C_struct_in_context, C_array, val_ty};
62 use context::CodegenCx;
67 use monomorphize::Instance;
68 use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
69 use rustc_codegen_utils::symbol_names_test;
71 use mono_item::{MonoItem, BaseMonoItemExt, MonoItemExt};
73 use type_of::LayoutLlvmExt;
74 use rustc::util::nodemap::{FxHashMap, FxHashSet, DefIdSet};
76 use rustc_data_structures::small_c_str::SmallCStr;
77 use rustc_data_structures::sync::Lrc;
80 use std::ffi::CString;
82 use std::time::{Instant, Duration};
87 use syntax_pos::symbol::InternedString;
89 use rustc::hir::{self, CodegenFnAttrs};
93 use mir::operand::OperandValue;
95 use rustc_codegen_utils::check_for_rustc_errors_attr;
97 pub struct StatRecorder<'a, 'll: 'a, 'tcx: 'll> {
98 cx: &'a CodegenCx<'ll, 'tcx>,
103 impl StatRecorder<'a, 'll, 'tcx> {
104 pub fn new(cx: &'a CodegenCx<'ll, 'tcx>, name: String) -> Self {
105 let istart = cx.stats.borrow().n_llvm_insns;
114 impl Drop for StatRecorder<'a, 'll, 'tcx> {
116 if self.cx.sess().codegen_stats() {
117 let mut stats = self.cx.stats.borrow_mut();
118 let iend = stats.n_llvm_insns;
119 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
121 // Reset LLVM insn count to avoid compound costs.
122 stats.n_llvm_insns = self.istart;
127 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
129 -> llvm::IntPredicate {
131 hir::BinOpKind::Eq => llvm::IntEQ,
132 hir::BinOpKind::Ne => llvm::IntNE,
133 hir::BinOpKind::Lt => if signed { llvm::IntSLT } else { llvm::IntULT },
134 hir::BinOpKind::Le => if signed { llvm::IntSLE } else { llvm::IntULE },
135 hir::BinOpKind::Gt => if signed { llvm::IntSGT } else { llvm::IntUGT },
136 hir::BinOpKind::Ge => if signed { llvm::IntSGE } else { llvm::IntUGE },
138 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
145 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> llvm::RealPredicate {
147 hir::BinOpKind::Eq => llvm::RealOEQ,
148 hir::BinOpKind::Ne => llvm::RealUNE,
149 hir::BinOpKind::Lt => llvm::RealOLT,
150 hir::BinOpKind::Le => llvm::RealOLE,
151 hir::BinOpKind::Gt => llvm::RealOGT,
152 hir::BinOpKind::Ge => llvm::RealOGE,
154 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
161 pub fn compare_simd_types(
162 bx: &Builder<'a, 'll, 'tcx>,
169 let signed = match t.sty {
171 let cmp = bin_op_to_fcmp_predicate(op);
172 return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
174 ty::TyUint(_) => false,
175 ty::TyInt(_) => true,
176 _ => bug!("compare_simd_types: invalid SIMD type"),
179 let cmp = bin_op_to_icmp_predicate(op, signed);
180 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
181 // to get the correctly sized type. This will compile to a single instruction
182 // once the IR is converted to assembly if the SIMD instruction is supported
183 // by the target architecture.
184 bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
187 /// Retrieve the information we are losing (making dynamic) in an unsizing
190 /// The `old_info` argument is a bit funny. It is intended for use
191 /// in an upcast, where the new vtable for an object will be derived
192 /// from the old one.
194 cx: &CodegenCx<'ll, 'tcx>,
197 old_info: Option<&'ll Value>,
199 let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
200 match (&source.sty, &target.sty) {
201 (&ty::TyArray(_, len), &ty::TySlice(_)) => {
202 C_usize(cx, len.unwrap_usize(cx.tcx))
204 (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
205 // For now, upcasts are limited to changes in marker
206 // traits, and hence never actually require an actual
207 // change to the vtable.
208 old_info.expect("unsized_info: missing old info for trait upcast")
210 (_, &ty::TyDynamic(ref data, ..)) => {
211 let vtable_ptr = cx.layout_of(cx.tcx.mk_mut_ptr(target))
212 .field(cx, abi::FAT_PTR_EXTRA);
213 consts::ptrcast(meth::get_vtable(cx, source, data.principal()),
214 vtable_ptr.llvm_type(cx))
216 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
222 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
223 pub fn unsize_thin_ptr(
224 bx: &Builder<'a, 'll, 'tcx>,
228 ) -> (&'ll Value, &'ll Value) {
229 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
230 match (&src_ty.sty, &dst_ty.sty) {
231 (&ty::TyRef(_, a, _),
232 &ty::TyRef(_, b, _)) |
233 (&ty::TyRef(_, a, _),
234 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
235 (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
236 &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
237 assert!(bx.cx.type_is_sized(a));
238 let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
239 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
241 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
242 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
243 assert!(bx.cx.type_is_sized(a));
244 let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
245 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
247 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
248 assert_eq!(def_a, def_b);
250 let src_layout = bx.cx.layout_of(src_ty);
251 let dst_layout = bx.cx.layout_of(dst_ty);
252 let mut result = None;
253 for i in 0..src_layout.fields.count() {
254 let src_f = src_layout.field(bx.cx, i);
255 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
256 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
260 assert_eq!(src_layout.size, src_f.size);
262 let dst_f = dst_layout.field(bx.cx, i);
263 assert_ne!(src_f.ty, dst_f.ty);
264 assert_eq!(result, None);
265 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
267 let (lldata, llextra) = result.unwrap();
268 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
269 (bx.bitcast(lldata, dst_layout.scalar_pair_element_llvm_type(bx.cx, 0, true)),
270 bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1, true)))
272 _ => bug!("unsize_thin_ptr: called on bad types"),
276 /// Coerce `src`, which is a reference to a value of type `src_ty`,
277 /// to a value of type `dst_ty` and store the result in `dst`
278 pub fn coerce_unsized_into(
279 bx: &Builder<'a, 'll, 'tcx>,
280 src: PlaceRef<'ll, 'tcx>,
281 dst: PlaceRef<'ll, 'tcx>
283 let src_ty = src.layout.ty;
284 let dst_ty = dst.layout.ty;
285 let coerce_ptr = || {
286 let (base, info) = match src.load(bx).val {
287 OperandValue::Pair(base, info) => {
288 // fat-ptr to fat-ptr unsize preserves the vtable
289 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
290 // So we need to pointercast the base to ensure
291 // the types match up.
292 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
293 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
295 OperandValue::Immediate(base) => {
296 unsize_thin_ptr(bx, base, src_ty, dst_ty)
298 OperandValue::Ref(..) | OperandValue::UnsizedRef(..) => bug!()
300 OperandValue::Pair(base, info).store(bx, dst);
302 match (&src_ty.sty, &dst_ty.sty) {
303 (&ty::TyRef(..), &ty::TyRef(..)) |
304 (&ty::TyRef(..), &ty::TyRawPtr(..)) |
305 (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
308 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
312 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
313 assert_eq!(def_a, def_b);
315 for i in 0..def_a.variants[0].fields.len() {
316 let src_f = src.project_field(bx, i);
317 let dst_f = dst.project_field(bx, i);
319 if dst_f.layout.is_zst() {
323 if src_f.layout.ty == dst_f.layout.ty {
324 memcpy_ty(bx, dst_f.llval, src_f.llval, src_f.layout,
325 src_f.align.min(dst_f.align), MemFlags::empty());
327 coerce_unsized_into(bx, src_f, dst_f);
331 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
337 pub fn cast_shift_expr_rhs(
338 cx: &Builder<'_, 'll, '_>, op: hir::BinOpKind, lhs: &'ll Value, rhs: &'ll Value
340 cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
343 fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
349 where F: FnOnce(&'ll Value, &'ll Type) -> &'ll Value,
350 G: FnOnce(&'ll Value, &'ll Type) -> &'ll Value
352 // Shifts may have any size int on the rhs
354 let mut rhs_llty = val_ty(rhs);
355 let mut lhs_llty = val_ty(lhs);
356 if rhs_llty.kind() == TypeKind::Vector {
357 rhs_llty = rhs_llty.element_type()
359 if lhs_llty.kind() == TypeKind::Vector {
360 lhs_llty = lhs_llty.element_type()
362 let rhs_sz = rhs_llty.int_width();
363 let lhs_sz = lhs_llty.int_width();
366 } else if lhs_sz > rhs_sz {
367 // FIXME (#1877: If shifting by negative
368 // values becomes not undefined then this is wrong.
378 /// Returns whether this session's target will use SEH-based unwinding.
380 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
381 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
382 /// 64-bit MinGW) instead of "full SEH".
383 pub fn wants_msvc_seh(sess: &Session) -> bool {
384 sess.target.target.options.is_like_msvc
387 pub fn call_assume(bx: &Builder<'_, 'll, '_>, val: &'ll Value) {
388 let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
389 bx.call(assume_intrinsic, &[val], None);
392 pub fn from_immediate(bx: &Builder<'_, 'll, '_>, val: &'ll Value) -> &'ll Value {
393 if val_ty(val) == Type::i1(bx.cx) {
394 bx.zext(val, Type::i8(bx.cx))
401 bx: &Builder<'_, 'll, '_>,
403 layout: layout::TyLayout,
405 if let layout::Abi::Scalar(ref scalar) = layout.abi {
406 return to_immediate_scalar(bx, val, scalar);
411 pub fn to_immediate_scalar(
412 bx: &Builder<'_, 'll, '_>,
414 scalar: &layout::Scalar,
416 if scalar.is_bool() {
417 return bx.trunc(val, Type::i1(bx.cx));
423 bx: &Builder<'_, 'll, '_>,
430 if flags.contains(MemFlags::NONTEMPORAL) {
431 // HACK(nox): This is inefficient but there is no nontemporal memcpy.
432 let val = bx.load(src, align);
433 let ptr = bx.pointercast(dst, val_ty(val).ptr_to());
434 bx.store_with_flags(val, ptr, align, flags);
438 let ptr_width = &cx.sess().target.target.target_pointer_width;
439 let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
440 let memcpy = cx.get_intrinsic(&key);
441 let src_ptr = bx.pointercast(src, Type::i8p(cx));
442 let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
443 let size = bx.intcast(n_bytes, cx.isize_ty, false);
444 let align = C_i32(cx, align.abi() as i32);
445 let volatile = C_bool(cx, flags.contains(MemFlags::VOLATILE));
446 bx.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
450 bx: &Builder<'_, 'll, 'tcx>,
453 layout: TyLayout<'tcx>,
457 let size = layout.size.bytes();
462 call_memcpy(bx, dst, src, C_usize(bx.cx, size), align, flags);
466 bx: &Builder<'_, 'll, '_>,
468 fill_byte: &'ll Value,
473 let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
474 let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
475 let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
476 let volatile = C_bool(bx.cx, volatile);
477 bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
480 pub fn codegen_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
481 let _s = if cx.sess().codegen_stats() {
482 let mut instance_name = String::new();
483 DefPathBasedNames::new(cx.tcx, true, true)
484 .push_def_path(instance.def_id(), &mut instance_name);
485 Some(StatRecorder::new(cx, instance_name))
490 // this is an info! to allow collecting monomorphization statistics
491 // and to allow finding the last function before LLVM aborts from
493 info!("codegen_instance({})", instance);
495 let fn_ty = instance.ty(cx.tcx);
496 let sig = common::ty_fn_sig(cx, fn_ty);
497 let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
499 let lldecl = match cx.instances.borrow().get(&instance) {
501 None => bug!("Instance `{:?}` not already declared", instance)
504 cx.stats.borrow_mut().n_closures += 1;
506 let mir = cx.tcx.instance_mir(instance.def);
507 mir::codegen_mir(cx, lldecl, &mir, instance, sig);
510 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
511 let sect = match attrs.link_section {
516 let buf = SmallCStr::new(§.as_str());
517 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(cx: &CodegenCx) {
524 let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
525 Some((id, span, _)) => {
526 (cx.tcx.hir.local_def_id(id), span)
531 let instance = Instance::mono(cx.tcx, main_def_id);
533 if !cx.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(cx, instance);
541 let et = cx.sess().entry_fn.get().map(|e| e.2);
543 Some(EntryFnType::Main) => create_entry_fn(cx, span, main_llfn, main_def_id, true),
544 Some(EntryFnType::Start) => create_entry_fn(cx, span, main_llfn, main_def_id, false),
545 None => {} // Do nothing.
549 cx: &CodegenCx<'ll, '_>,
551 rust_main: &'ll Value,
552 rust_main_def_id: DefId,
553 use_start_lang_item: bool,
555 let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], Type::c_int(cx));
557 let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
558 // Given that `main()` has no arguments,
559 // then its return type cannot have
560 // late-bound regions, since late-bound
561 // regions must appear in the argument
563 let main_ret_ty = cx.tcx.erase_regions(
564 &main_ret_ty.no_late_bound_regions().unwrap(),
567 if declare::get_defined_value(cx, "main").is_some() {
568 // FIXME: We should be smart and show a better diagnostic here.
569 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
570 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
572 cx.sess().abort_if_errors();
575 let llfn = declare::declare_cfn(cx, "main", llfty);
577 // `main` should respect same config for frame pointer elimination as rest of code
578 attributes::set_frame_pointer_elimination(cx, llfn);
579 attributes::apply_target_cpu_attr(cx, llfn);
581 let bx = Builder::new_block(cx, llfn, "top");
583 debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
585 // Params from native main() used as args for rust start function
586 let param_argc = get_param(llfn, 0);
587 let param_argv = get_param(llfn, 1);
588 let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
589 let arg_argv = param_argv;
591 let (start_fn, args) = if use_start_lang_item {
592 let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
593 let start_fn = callee::resolve_and_get_fn(
596 cx.tcx.intern_substs(&[main_ret_ty.into()]),
598 (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
601 debug!("using user-defined start fn");
602 (rust_main, vec![arg_argc, arg_argv])
605 let result = bx.call(start_fn, &args, None);
606 bx.ret(bx.intcast(result, Type::c_int(cx), true));
610 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
611 llvm_module: &ModuleLlvm,
612 link_meta: &LinkMeta)
615 use flate2::Compression;
616 use flate2::write::DeflateEncoder;
618 let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
620 #[derive(PartialEq, Eq, PartialOrd, Ord)]
627 let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
629 config::CrateType::Executable |
630 config::CrateType::Staticlib |
631 config::CrateType::Cdylib => MetadataKind::None,
633 config::CrateType::Rlib => MetadataKind::Uncompressed,
635 config::CrateType::Dylib |
636 config::CrateType::ProcMacro => MetadataKind::Compressed,
638 }).max().unwrap_or(MetadataKind::None);
640 if kind == MetadataKind::None {
641 return EncodedMetadata::new();
644 let metadata = tcx.encode_metadata(link_meta);
645 if kind == MetadataKind::Uncompressed {
649 assert!(kind == MetadataKind::Compressed);
650 let mut compressed = tcx.metadata_encoding_version();
651 DeflateEncoder::new(&mut compressed, Compression::fast())
652 .write_all(&metadata.raw_data).unwrap();
654 let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
655 let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
656 let name = exported_symbols::metadata_symbol_name(tcx);
657 let buf = CString::new(name).unwrap();
658 let llglobal = unsafe {
659 llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst), buf.as_ptr())
662 llvm::LLVMSetInitializer(llglobal, llconst);
663 let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
664 let name = SmallCStr::new(section_name);
665 llvm::LLVMSetSection(llglobal, name.as_ptr());
667 // Also generate a .section directive to force no
668 // flags, at least for ELF outputs, so that the
669 // metadata doesn't get loaded into memory.
670 let directive = format!(".section {}", section_name);
671 let directive = CString::new(directive).unwrap();
672 llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
677 pub struct ValueIter<'ll> {
678 cur: Option<&'ll Value>,
679 step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
682 impl Iterator for ValueIter<'ll> {
683 type Item = &'ll Value;
685 fn next(&mut self) -> Option<&'ll Value> {
687 if let Some(old) = old {
688 self.cur = unsafe { (self.step)(old) };
694 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
697 cur: llvm::LLVMGetFirstGlobal(llmod),
698 step: llvm::LLVMGetNextGlobal,
703 pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
704 rx: mpsc::Receiver<Box<dyn Any + Send>>)
707 check_for_rustc_errors_attr(tcx);
709 if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
710 if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
711 tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
715 if (tcx.sess.opts.debugging_opts.pgo_gen.is_some() ||
716 !tcx.sess.opts.debugging_opts.pgo_use.is_empty()) &&
717 unsafe { !llvm::LLVMRustPGOAvailable() }
719 tcx.sess.fatal("this compiler's LLVM does not support PGO");
722 let crate_hash = tcx.crate_hash(LOCAL_CRATE);
723 let link_meta = link::build_link_meta(crate_hash);
724 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
726 // Codegen the metadata.
727 tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
729 let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
731 Some("metadata")).as_str()
733 let metadata_llvm_module = ModuleLlvm::new(tcx.sess, &metadata_cgu_name);
734 let metadata = time(tcx.sess, "write metadata", || {
735 write_metadata(tcx, &metadata_llvm_module, &link_meta)
737 tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
739 let metadata_module = ModuleCodegen {
740 name: metadata_cgu_name,
741 source: ModuleSource::Codegened(metadata_llvm_module),
742 kind: ModuleKind::Metadata,
745 let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
746 Some(time_graph::TimeGraph::new())
751 // Skip crate items and just output metadata in -Z no-codegen mode.
752 if tcx.sess.opts.debugging_opts.no_codegen ||
753 !tcx.sess.opts.output_types.should_codegen() {
754 let ongoing_codegen = write::start_async_codegen(
762 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
763 ongoing_codegen.codegen_finished(tcx);
765 assert_and_save_dep_graph(tcx);
767 ongoing_codegen.check_for_errors(tcx.sess);
769 return ongoing_codegen;
772 // Run the monomorphization collector and partition the collected items into
775 tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
776 let codegen_units = (*codegen_units).clone();
778 // Force all codegen_unit queries so they are already either red or green
779 // when compile_codegen_unit accesses them. We are not able to re-execute
780 // the codegen_unit query from just the DepNode, so an unknown color would
781 // lead to having to re-execute compile_codegen_unit, possibly
783 if tcx.dep_graph.is_fully_enabled() {
784 for cgu in &codegen_units {
785 tcx.codegen_unit(cgu.name().clone());
789 let ongoing_codegen = write::start_async_codegen(
795 codegen_units.len());
797 // Codegen an allocator shim, if necessary.
799 // If the crate doesn't have an `allocator_kind` set then there's definitely
800 // no shim to generate. Otherwise we also check our dependency graph for all
801 // our output crate types. If anything there looks like its a `Dynamic`
802 // linkage, then it's already got an allocator shim and we'll be using that
803 // one instead. If nothing exists then it's our job to generate the
805 let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
808 use rustc::middle::dependency_format::Linkage;
809 list.iter().any(|linkage| {
811 Linkage::Dynamic => true,
816 let allocator_module = if any_dynamic_crate {
818 } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
819 let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
821 Some("allocator")).as_str()
823 let modules = ModuleLlvm::new(tcx.sess, &llmod_id);
824 time(tcx.sess, "write allocator module", || {
826 allocator::codegen(tcx, &modules, kind)
832 source: ModuleSource::Codegened(modules),
833 kind: ModuleKind::Allocator,
839 if let Some(allocator_module) = allocator_module {
840 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
843 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
845 // We sort the codegen units by size. This way we can schedule work for LLVM
846 // a bit more efficiently.
847 let codegen_units = {
848 let mut codegen_units = codegen_units;
849 codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
853 let mut total_codegen_time = Duration::new(0, 0);
854 let mut all_stats = Stats::default();
856 for cgu in codegen_units.into_iter() {
857 ongoing_codegen.wait_for_signal_to_codegen_item();
858 ongoing_codegen.check_for_errors(tcx.sess);
860 // First, if incremental compilation is enabled, we try to re-use the
861 // codegen unit from the cache.
862 if tcx.dep_graph.is_fully_enabled() {
863 let cgu_id = cgu.work_product_id();
865 // Check whether there is a previous work-product we can
866 // re-use. Not only must the file exist, and the inputs not
867 // be dirty, but the hash of the symbols we will generate must
869 if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
870 let dep_node = &DepNode::new(tcx,
871 DepConstructor::CompileCodegenUnit(cgu.name().clone()));
873 // We try to mark the DepNode::CompileCodegenUnit green. If we
874 // succeed it means that none of the dependencies has changed
875 // and we can safely re-use.
876 if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
877 let module = ModuleCodegen {
878 name: cgu.name().to_string(),
879 source: ModuleSource::Preexisting(buf),
880 kind: ModuleKind::Regular,
882 tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
883 write::submit_codegened_module_to_llvm(tcx, module, 0);
884 // Continue to next cgu, this one is done.
888 // This can happen if files were deleted from the cache
889 // directory for some reason. We just re-compile then.
893 let _timing_guard = time_graph.as_ref().map(|time_graph| {
894 time_graph.start(write::CODEGEN_WORKER_TIMELINE,
895 write::CODEGEN_WORK_PACKAGE_KIND,
896 &format!("codegen {}", cgu.name()))
898 let start_time = Instant::now();
899 all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
900 total_codegen_time += start_time.elapsed();
901 ongoing_codegen.check_for_errors(tcx.sess);
904 ongoing_codegen.codegen_finished(tcx);
906 // Since the main thread is sometimes blocked during codegen, we keep track
907 // -Ztime-passes output manually.
908 print_time_passes_entry(tcx.sess.time_passes(),
909 "codegen to LLVM IR",
912 if tcx.sess.opts.incremental.is_some() {
913 ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
916 symbol_names_test::report_symbol_names(tcx);
918 if tcx.sess.codegen_stats() {
919 println!("--- codegen stats ---");
920 println!("n_glues_created: {}", all_stats.n_glues_created);
921 println!("n_null_glues: {}", all_stats.n_null_glues);
922 println!("n_real_glues: {}", all_stats.n_real_glues);
924 println!("n_fns: {}", all_stats.n_fns);
925 println!("n_inlines: {}", all_stats.n_inlines);
926 println!("n_closures: {}", all_stats.n_closures);
927 println!("fn stats:");
928 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
929 for &(ref name, insns) in all_stats.fn_stats.iter() {
930 println!("{} insns, {}", insns, *name);
934 if tcx.sess.count_llvm_insns() {
935 for (k, v) in all_stats.llvm_insns.iter() {
936 println!("{:7} {}", *v, *k);
940 ongoing_codegen.check_for_errors(tcx.sess);
942 assert_and_save_dep_graph(tcx);
946 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
949 || rustc_incremental::assert_dep_graph(tcx));
952 "serialize dep graph",
953 || rustc_incremental::save_dep_graph(tcx));
956 fn collect_and_partition_mono_items<'a, 'tcx>(
957 tcx: TyCtxt<'a, 'tcx, 'tcx>,
959 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
961 assert_eq!(cnum, LOCAL_CRATE);
963 let collection_mode = match tcx.sess.opts.debugging_opts.print_mono_items {
965 let mode_string = s.to_lowercase();
966 let mode_string = mode_string.trim();
967 if mode_string == "eager" {
968 MonoItemCollectionMode::Eager
970 if mode_string != "lazy" {
971 let message = format!("Unknown codegen-item collection mode '{}'. \
972 Falling back to 'lazy' mode.",
974 tcx.sess.warn(&message);
977 MonoItemCollectionMode::Lazy
981 if tcx.sess.opts.cg.link_dead_code {
982 MonoItemCollectionMode::Eager
984 MonoItemCollectionMode::Lazy
989 let (items, inlining_map) =
990 time(tcx.sess, "monomorphization collection", || {
991 collector::collect_crate_mono_items(tcx, collection_mode)
994 tcx.sess.abort_if_errors();
996 ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
998 let strategy = if tcx.sess.opts.incremental.is_some() {
999 PartitioningStrategy::PerModule
1001 PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
1004 let codegen_units = time(tcx.sess, "codegen unit partitioning", || {
1005 partitioning::partition(tcx,
1006 items.iter().cloned(),
1011 .collect::<Vec<_>>()
1014 let mono_items: DefIdSet = items.iter().filter_map(|mono_item| {
1016 MonoItem::Fn(ref instance) => Some(instance.def_id()),
1017 MonoItem::Static(def_id) => Some(def_id),
1022 if tcx.sess.opts.debugging_opts.print_mono_items.is_some() {
1023 let mut item_to_cgus = FxHashMap();
1025 for cgu in &codegen_units {
1026 for (&mono_item, &linkage) in cgu.items() {
1027 item_to_cgus.entry(mono_item)
1028 .or_insert(Vec::new())
1029 .push((cgu.name().clone(), linkage));
1033 let mut item_keys: Vec<_> = items
1036 let mut output = i.to_string(tcx);
1037 output.push_str(" @@");
1038 let mut empty = Vec::new();
1039 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1040 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1042 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1043 output.push_str(" ");
1044 output.push_str(&cgu_name.as_str());
1046 let linkage_abbrev = match linkage {
1047 Linkage::External => "External",
1048 Linkage::AvailableExternally => "Available",
1049 Linkage::LinkOnceAny => "OnceAny",
1050 Linkage::LinkOnceODR => "OnceODR",
1051 Linkage::WeakAny => "WeakAny",
1052 Linkage::WeakODR => "WeakODR",
1053 Linkage::Appending => "Appending",
1054 Linkage::Internal => "Internal",
1055 Linkage::Private => "Private",
1056 Linkage::ExternalWeak => "ExternalWeak",
1057 Linkage::Common => "Common",
1060 output.push_str("[");
1061 output.push_str(linkage_abbrev);
1062 output.push_str("]");
1070 for item in item_keys {
1071 println!("MONO_ITEM {}", item);
1075 (Arc::new(mono_items), Arc::new(codegen_units))
1079 pub fn new(tcx: TyCtxt) -> CrateInfo {
1080 let mut info = CrateInfo {
1081 panic_runtime: None,
1082 compiler_builtins: None,
1083 profiler_runtime: None,
1084 sanitizer_runtime: None,
1085 is_no_builtins: FxHashSet(),
1086 native_libraries: FxHashMap(),
1087 used_libraries: tcx.native_libraries(LOCAL_CRATE),
1088 link_args: tcx.link_args(LOCAL_CRATE),
1089 crate_name: FxHashMap(),
1090 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1091 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1092 used_crate_source: FxHashMap(),
1093 wasm_imports: FxHashMap(),
1094 lang_item_to_crate: FxHashMap(),
1095 missing_lang_items: FxHashMap(),
1097 let lang_items = tcx.lang_items();
1099 let load_wasm_items = tcx.sess.crate_types.borrow()
1101 .any(|c| *c != config::CrateType::Rlib) &&
1102 tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
1104 if load_wasm_items {
1105 info.load_wasm_imports(tcx, LOCAL_CRATE);
1108 for &cnum in tcx.crates().iter() {
1109 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1110 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1111 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1112 if tcx.is_panic_runtime(cnum) {
1113 info.panic_runtime = Some(cnum);
1115 if tcx.is_compiler_builtins(cnum) {
1116 info.compiler_builtins = Some(cnum);
1118 if tcx.is_profiler_runtime(cnum) {
1119 info.profiler_runtime = Some(cnum);
1121 if tcx.is_sanitizer_runtime(cnum) {
1122 info.sanitizer_runtime = Some(cnum);
1124 if tcx.is_no_builtins(cnum) {
1125 info.is_no_builtins.insert(cnum);
1127 if load_wasm_items {
1128 info.load_wasm_imports(tcx, cnum);
1130 let missing = tcx.missing_lang_items(cnum);
1131 for &item in missing.iter() {
1132 if let Ok(id) = lang_items.require(item) {
1133 info.lang_item_to_crate.insert(item, id.krate);
1137 // No need to look for lang items that are whitelisted and don't
1138 // actually need to exist.
1139 let missing = missing.iter()
1141 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
1143 info.missing_lang_items.insert(cnum, missing);
1149 fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1150 for (&id, module) in tcx.wasm_import_module_map(cnum).iter() {
1151 let instance = Instance::mono(tcx, id);
1152 let import_name = tcx.symbol_name(instance);
1153 self.wasm_imports.insert(import_name.to_string(), module.clone());
1158 fn is_codegened_item(tcx: TyCtxt, id: DefId) -> bool {
1159 let (all_mono_items, _) =
1160 tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1161 all_mono_items.contains(&id)
1164 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1165 cgu: InternedString) -> Stats {
1166 let cgu = tcx.codegen_unit(cgu);
1168 let start_time = Instant::now();
1169 let (stats, module) = module_codegen(tcx, cgu);
1170 let time_to_codegen = start_time.elapsed();
1172 // We assume that the cost to run LLVM on a CGU is proportional to
1173 // the time we needed for codegenning it.
1174 let cost = time_to_codegen.as_secs() * 1_000_000_000 +
1175 time_to_codegen.subsec_nanos() as u64;
1177 write::submit_codegened_module_to_llvm(tcx,
1182 fn module_codegen<'a, 'tcx>(
1183 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1184 cgu: Arc<CodegenUnit<'tcx>>)
1185 -> (Stats, ModuleCodegen)
1187 let cgu_name = cgu.name().to_string();
1189 // Instantiate monomorphizations without filling out definitions yet...
1190 let llvm_module = ModuleLlvm::new(tcx.sess, &cgu_name);
1192 let cx = CodegenCx::new(tcx, cgu, &llvm_module);
1193 let mono_items = cx.codegen_unit
1194 .items_in_deterministic_order(cx.tcx);
1195 for &(mono_item, (linkage, visibility)) in &mono_items {
1196 mono_item.predefine(&cx, linkage, visibility);
1199 // ... and now that we have everything pre-defined, fill out those definitions.
1200 for &(mono_item, _) in &mono_items {
1201 mono_item.define(&cx);
1204 // If this codegen unit contains the main function, also create the
1206 maybe_create_entry_wrapper(&cx);
1208 // Run replace-all-uses-with for statics that need it
1209 for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1211 let bitcast = llvm::LLVMConstPointerCast(new_g, val_ty(old_g));
1212 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1213 llvm::LLVMDeleteGlobal(old_g);
1217 // Create the llvm.used variable
1218 // This variable has type [N x i8*] and is stored in the llvm.metadata section
1219 if !cx.used_statics.borrow().is_empty() {
1220 let name = const_cstr!("llvm.used");
1221 let section = const_cstr!("llvm.metadata");
1222 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1225 let g = llvm::LLVMAddGlobal(cx.llmod,
1228 llvm::LLVMSetInitializer(g, array);
1229 llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1230 llvm::LLVMSetSection(g, section.as_ptr());
1234 // Finalize debuginfo
1235 if cx.sess().opts.debuginfo != DebugInfo::None {
1236 debuginfo::finalize(&cx);
1239 cx.stats.into_inner()
1242 (stats, ModuleCodegen {
1244 source: ModuleSource::Codegened(llvm_module),
1245 kind: ModuleKind::Regular,
1250 pub fn provide(providers: &mut Providers) {
1251 providers.collect_and_partition_mono_items =
1252 collect_and_partition_mono_items;
1254 providers.is_codegened_item = is_codegened_item;
1256 providers.codegen_unit = |tcx, name| {
1257 let (_, all) = tcx.collect_and_partition_mono_items(LOCAL_CRATE);
1259 .find(|cgu| *cgu.name() == name)
1261 .unwrap_or_else(|| panic!("failed to find cgu with name {:?}", name))
1263 providers.compile_codegen_unit = compile_codegen_unit;
1265 provide_extern(providers);
1268 pub fn provide_extern(providers: &mut Providers) {
1269 providers.dllimport_foreign_items = |tcx, krate| {
1270 let module_map = tcx.foreign_modules(krate);
1271 let module_map = module_map.iter()
1272 .map(|lib| (lib.def_id, lib))
1273 .collect::<FxHashMap<_, _>>();
1275 let dllimports = tcx.native_libraries(krate)
1278 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1281 let cfg = match lib.cfg {
1282 Some(ref cfg) => cfg,
1283 None => return true,
1285 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1287 .filter_map(|lib| lib.foreign_module)
1288 .map(|id| &module_map[&id])
1289 .flat_map(|module| module.foreign_items.iter().cloned())
1291 Lrc::new(dllimports)
1294 providers.is_dllimport_foreign_item = |tcx, def_id| {
1295 tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1299 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1301 Linkage::External => llvm::Linkage::ExternalLinkage,
1302 Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1303 Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1304 Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1305 Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1306 Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1307 Linkage::Appending => llvm::Linkage::AppendingLinkage,
1308 Linkage::Internal => llvm::Linkage::InternalLinkage,
1309 Linkage::Private => llvm::Linkage::PrivateLinkage,
1310 Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1311 Linkage::Common => llvm::Linkage::CommonLinkage,
1315 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1317 Visibility::Default => llvm::Visibility::Default,
1318 Visibility::Hidden => llvm::Visibility::Hidden,
1319 Visibility::Protected => llvm::Visibility::Protected,
1323 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1324 // the HashStable trait. Normally DepGraph::with_task() calls are
1325 // hidden behind queries, but CGU creation is a special case in two
1326 // ways: (1) it's not a query and (2) CGU are output nodes, so their
1327 // Fingerprints are not actually needed. It remains to be clarified
1328 // how exactly this case will be handled in the red/green system but
1329 // for now we content ourselves with providing a no-op HashStable
1330 // implementation for CGUs.
1331 mod temp_stable_hash_impls {
1332 use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1336 impl<HCX> HashStable<HCX> for ModuleCodegen {
1337 fn hash_stable<W: StableHasherResult>(&self,
1339 _: &mut StableHasher<W>) {