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 {ModuleCodegen, ModuleKind, CachedModuleCodegen};
28 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
29 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
30 use rustc::middle::lang_items::StartFnLangItem;
31 use rustc::middle::weak_lang_items;
32 use rustc::mir::mono::{Stats, CodegenUnitNameBuilder};
33 use rustc::ty::{self, Ty, TyCtxt};
34 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, VariantIdx, HasTyCtxt};
35 use rustc::ty::query::Providers;
36 use rustc::middle::cstore::{self, LinkagePreference};
37 use rustc::util::common::{time, print_time_passes_entry};
38 use rustc::util::profiling::ProfileCategory;
39 use rustc::session::config::{self, EntryFnType, Lto};
40 use rustc::session::Session;
41 use mir::place::PlaceRef;
42 use back::write::{OngoingCodegen, start_async_codegen, submit_pre_lto_module_to_llvm,
43 submit_post_lto_module_to_llvm};
44 use {MemFlags, CrateInfo};
46 use rustc_mir::monomorphize::item::DefPathBasedNames;
47 use common::{RealPredicate, TypeKind, IntPredicate};
50 use rustc::util::time_graph;
51 use rustc_mir::monomorphize::Instance;
52 use rustc_mir::monomorphize::partitioning::{CodegenUnit, CodegenUnitExt};
53 use mono_item::MonoItem;
54 use rustc::util::nodemap::FxHashMap;
55 use rustc_data_structures::indexed_vec::Idx;
56 use rustc_data_structures::sync::Lrc;
57 use rustc_codegen_utils::{symbol_names_test, check_for_rustc_errors_attr};
58 use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
64 use std::ops::{Deref, DerefMut};
65 use std::time::{Instant, Duration};
71 use mir::operand::OperandValue;
73 use std::marker::PhantomData;
75 pub struct StatRecorder<'a, 'tcx, Cx: 'a + CodegenMethods<'tcx>> {
79 _marker: PhantomData<&'tcx ()>,
82 impl<'a, 'tcx, Cx: CodegenMethods<'tcx>> StatRecorder<'a, 'tcx, Cx> {
83 pub fn new(cx: &'a Cx, name: String) -> Self {
84 let istart = cx.stats().borrow().n_llvm_insns;
94 impl<'a, 'tcx, Cx: CodegenMethods<'tcx>> Drop for StatRecorder<'a, 'tcx, Cx> {
96 if self.cx.sess().codegen_stats() {
97 let mut stats = self.cx.stats().borrow_mut();
98 let iend = stats.n_llvm_insns;
99 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
101 // Reset LLVM insn count to avoid compound costs.
102 stats.n_llvm_insns = self.istart;
107 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
111 hir::BinOpKind::Eq => IntPredicate::IntEQ,
112 hir::BinOpKind::Ne => IntPredicate::IntNE,
113 hir::BinOpKind::Lt => if signed { IntPredicate::IntSLT } else { IntPredicate::IntULT },
114 hir::BinOpKind::Le => if signed { IntPredicate::IntSLE } else { IntPredicate::IntULE },
115 hir::BinOpKind::Gt => if signed { IntPredicate::IntSGT } else { IntPredicate::IntUGT },
116 hir::BinOpKind::Ge => if signed { IntPredicate::IntSGE } else { IntPredicate::IntUGE },
118 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
125 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
127 hir::BinOpKind::Eq => RealPredicate::RealOEQ,
128 hir::BinOpKind::Ne => RealPredicate::RealUNE,
129 hir::BinOpKind::Lt => RealPredicate::RealOLT,
130 hir::BinOpKind::Le => RealPredicate::RealOLE,
131 hir::BinOpKind::Gt => RealPredicate::RealOGT,
132 hir::BinOpKind::Ge => RealPredicate::RealOGE,
134 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
141 pub fn compare_simd_types<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
149 let signed = match t.sty {
151 let cmp = bin_op_to_fcmp_predicate(op);
152 let cmp = bx.fcmp(cmp, lhs, rhs);
153 return bx.sext(cmp, ret_ty);
155 ty::Uint(_) => false,
157 _ => bug!("compare_simd_types: invalid SIMD type"),
160 let cmp = bin_op_to_icmp_predicate(op, signed);
161 let cmp = bx.icmp(cmp, lhs, rhs);
162 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
163 // to get the correctly sized type. This will compile to a single instruction
164 // once the IR is converted to assembly if the SIMD instruction is supported
165 // by the target architecture.
169 /// Retrieve the information we are losing (making dynamic) in an unsizing
172 /// The `old_info` argument is a bit funny. It is intended for use
173 /// in an upcast, where the new vtable for an object will be derived
174 /// from the old one.
175 pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>(
179 old_info: Option<Cx::Value>,
181 let (source, target) = cx.tcx().struct_lockstep_tails(source, target);
182 match (&source.sty, &target.sty) {
183 (&ty::Array(_, len), &ty::Slice(_)) => {
184 cx.const_usize(len.unwrap_usize(cx.tcx()))
186 (&ty::Dynamic(..), &ty::Dynamic(..)) => {
187 // For now, upcasts are limited to changes in marker
188 // traits, and hence never actually require an actual
189 // change to the vtable.
190 old_info.expect("unsized_info: missing old info for trait upcast")
192 (_, &ty::Dynamic(ref data, ..)) => {
193 let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target))
194 .field(cx, FAT_PTR_EXTRA);
195 cx.const_ptrcast(meth::get_vtable(cx, source, data.principal()),
196 cx.backend_type(vtable_ptr))
198 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
204 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
205 pub fn unsize_thin_ptr<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
210 ) -> (Bx::Value, Bx::Value) {
211 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
212 match (&src_ty.sty, &dst_ty.sty) {
216 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
217 (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
218 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
219 assert!(bx.cx().type_is_sized(a));
220 let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
221 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
223 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
224 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
225 assert!(bx.cx().type_is_sized(a));
226 let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
227 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
229 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
230 assert_eq!(def_a, def_b);
232 let src_layout = bx.cx().layout_of(src_ty);
233 let dst_layout = bx.cx().layout_of(dst_ty);
234 let mut result = None;
235 for i in 0..src_layout.fields.count() {
236 let src_f = src_layout.field(bx.cx(), i);
237 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
238 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
242 assert_eq!(src_layout.size, src_f.size);
244 let dst_f = dst_layout.field(bx.cx(), i);
245 assert_ne!(src_f.ty, dst_f.ty);
246 assert_eq!(result, None);
247 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
249 let (lldata, llextra) = result.unwrap();
250 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
251 (bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)),
252 bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true)))
254 _ => bug!("unsize_thin_ptr: called on bad types"),
258 /// Coerce `src`, which is a reference to a value of type `src_ty`,
259 /// to a value of type `dst_ty` and store the result in `dst`
260 pub fn coerce_unsized_into<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
262 src: PlaceRef<'tcx, Bx::Value>,
263 dst: PlaceRef<'tcx, Bx::Value>
265 let src_ty = src.layout.ty;
266 let dst_ty = dst.layout.ty;
267 let mut coerce_ptr = || {
268 let (base, info) = match bx.load_operand(src).val {
269 OperandValue::Pair(base, info) => {
270 // fat-ptr to fat-ptr unsize preserves the vtable
271 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
272 // So we need to pointercast the base to ensure
273 // the types match up.
274 let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR);
275 (bx.pointercast(base, bx.cx().backend_type(thin_ptr)), info)
277 OperandValue::Immediate(base) => {
278 unsize_thin_ptr(bx, base, src_ty, dst_ty)
280 OperandValue::Ref(..) => bug!()
282 OperandValue::Pair(base, info).store(bx, dst);
284 match (&src_ty.sty, &dst_ty.sty) {
285 (&ty::Ref(..), &ty::Ref(..)) |
286 (&ty::Ref(..), &ty::RawPtr(..)) |
287 (&ty::RawPtr(..), &ty::RawPtr(..)) => {
290 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
294 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
295 assert_eq!(def_a, def_b);
297 for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
298 let src_f = src.project_field(bx, i);
299 let dst_f = dst.project_field(bx, i);
301 if dst_f.layout.is_zst() {
305 if src_f.layout.ty == dst_f.layout.ty {
306 memcpy_ty(bx, dst_f.llval, dst_f.align, src_f.llval, src_f.align,
307 src_f.layout, MemFlags::empty());
309 coerce_unsized_into(bx, src_f, dst_f);
313 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
319 pub fn cast_shift_expr_rhs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
325 cast_shift_rhs(bx, op, lhs, rhs)
328 fn cast_shift_rhs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
334 // Shifts may have any size int on the rhs
336 let mut rhs_llty = bx.cx().val_ty(rhs);
337 let mut lhs_llty = bx.cx().val_ty(lhs);
338 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
339 rhs_llty = bx.cx().element_type(rhs_llty)
341 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
342 lhs_llty = bx.cx().element_type(lhs_llty)
344 let rhs_sz = bx.cx().int_width(rhs_llty);
345 let lhs_sz = bx.cx().int_width(lhs_llty);
347 bx.trunc(rhs, lhs_llty)
348 } else if lhs_sz > rhs_sz {
349 // FIXME (#1877: If in the future shifting by negative
350 // values is no longer undefined then this is wrong.
351 bx.zext(rhs, lhs_llty)
360 /// Returns whether this session's target will use SEH-based unwinding.
362 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
363 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
364 /// 64-bit MinGW) instead of "full SEH".
365 pub fn wants_msvc_seh(sess: &Session) -> bool {
366 sess.target.target.options.is_like_msvc
369 pub fn from_immediate<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
373 if bx.cx().val_ty(val) == bx.cx().type_i1() {
374 bx.zext(val, bx.cx().type_i8())
380 pub fn to_immediate<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
383 layout: layout::TyLayout,
385 if let layout::Abi::Scalar(ref scalar) = layout.abi {
386 return to_immediate_scalar(bx, val, scalar);
391 pub fn to_immediate_scalar<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
394 scalar: &layout::Scalar,
396 if scalar.is_bool() {
397 return bx.trunc(val, bx.cx().type_i1());
402 pub fn memcpy_ty<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
408 layout: TyLayout<'tcx>,
411 let size = layout.size.bytes();
416 bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
419 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
420 cx: &'a Bx::CodegenCx,
421 instance: Instance<'tcx>,
423 let _s = if cx.sess().codegen_stats() {
424 let mut instance_name = String::new();
425 DefPathBasedNames::new(cx.tcx(), true, true)
426 .push_def_path(instance.def_id(), &mut instance_name);
427 Some(StatRecorder::new(cx, instance_name))
432 // this is an info! to allow collecting monomorphization statistics
433 // and to allow finding the last function before LLVM aborts from
435 info!("codegen_instance({})", instance);
437 let sig = instance.fn_sig(cx.tcx());
438 let sig = cx.tcx().normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
440 let lldecl = cx.instances().borrow().get(&instance).cloned().unwrap_or_else(||
441 bug!("Instance `{:?}` not already declared", instance));
443 cx.stats().borrow_mut().n_closures += 1;
445 let mir = cx.tcx().instance_mir(instance.def);
446 mir::codegen_mir::<Bx>(cx, lldecl, &mir, instance, sig);
449 /// Create the `main` function which will initialize the rust runtime and call
450 /// users main function.
451 pub fn maybe_create_entry_wrapper<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
452 cx: &'a Bx::CodegenCx
454 let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
455 Some((id, span, _)) => {
456 (cx.tcx().hir().local_def_id(id), span)
461 let instance = Instance::mono(cx.tcx(), main_def_id);
463 if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
464 // We want to create the wrapper in the same codegen unit as Rust's main
469 let main_llfn = cx.get_fn(instance);
471 let et = cx.sess().entry_fn.get().map(|e| e.2);
473 Some(EntryFnType::Main) => create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, true),
474 Some(EntryFnType::Start) => create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, false),
475 None => {} // Do nothing.
478 fn create_entry_fn<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
479 cx: &'a Bx::CodegenCx,
481 rust_main: Bx::Value,
482 rust_main_def_id: DefId,
483 use_start_lang_item: bool,
486 cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int());
488 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
489 // Given that `main()` has no arguments,
490 // then its return type cannot have
491 // late-bound regions, since late-bound
492 // regions must appear in the argument
494 let main_ret_ty = cx.tcx().erase_regions(
495 &main_ret_ty.no_bound_vars().unwrap(),
498 if cx.get_defined_value("main").is_some() {
499 // FIXME: We should be smart and show a better diagnostic here.
500 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
501 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
503 cx.sess().abort_if_errors();
506 let llfn = cx.declare_cfn("main", llfty);
508 // `main` should respect same config for frame pointer elimination as rest of code
509 cx.set_frame_pointer_elimination(llfn);
510 cx.apply_target_cpu_attr(llfn);
512 let mut bx = Bx::new_block(&cx, llfn, "top");
514 bx.insert_reference_to_gdb_debug_scripts_section_global();
516 // Params from native main() used as args for rust start function
517 let param_argc = cx.get_param(llfn, 0);
518 let param_argv = cx.get_param(llfn, 1);
519 let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
520 let arg_argv = param_argv;
522 let (start_fn, args) = if use_start_lang_item {
523 let start_def_id = cx.tcx().require_lang_item(StartFnLangItem);
524 let start_fn = callee::resolve_and_get_fn(
527 cx.tcx().intern_substs(&[main_ret_ty.into()]),
529 (start_fn, vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())),
532 debug!("using user-defined start fn");
533 (rust_main, vec![arg_argc, arg_argv])
536 let result = bx.call(start_fn, &args, None);
537 let cast = bx.intcast(result, cx.type_int(), true);
542 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
543 pub const CODEGEN_WORKER_TIMELINE: time_graph::TimelineId =
544 time_graph::TimelineId(CODEGEN_WORKER_ID);
545 pub const CODEGEN_WORK_PACKAGE_KIND: time_graph::WorkPackageKind =
546 time_graph::WorkPackageKind(&["#DE9597", "#FED1D3", "#FDC5C7", "#B46668", "#88494B"]);
549 pub fn codegen_crate<B: ExtraBackendMethods>(
551 tcx: TyCtxt<'a, 'tcx, 'tcx>,
552 rx: mpsc::Receiver<Box<dyn Any + Send>>
553 ) -> OngoingCodegen<B> {
555 check_for_rustc_errors_attr(tcx);
557 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
559 // Codegen the metadata.
560 tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
562 let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
564 Some("metadata")).as_str()
566 let metadata_llvm_module = backend.new_metadata(tcx.sess, &metadata_cgu_name);
567 let metadata = time(tcx.sess, "write metadata", || {
568 backend.write_metadata(tcx, &metadata_llvm_module)
570 tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
572 let metadata_module = ModuleCodegen {
573 name: metadata_cgu_name,
574 module_llvm: metadata_llvm_module,
575 kind: ModuleKind::Metadata,
578 let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
579 Some(time_graph::TimeGraph::new())
584 // Skip crate items and just output metadata in -Z no-codegen mode.
585 if tcx.sess.opts.debugging_opts.no_codegen ||
586 !tcx.sess.opts.output_types.should_codegen() {
587 let ongoing_codegen = start_async_codegen(
595 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
596 ongoing_codegen.codegen_finished(tcx);
598 assert_and_save_dep_graph(tcx);
600 ongoing_codegen.check_for_errors(tcx.sess);
602 return ongoing_codegen;
605 // Run the monomorphization collector and partition the collected items into
607 let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
608 let codegen_units = (*codegen_units).clone();
610 // Force all codegen_unit queries so they are already either red or green
611 // when compile_codegen_unit accesses them. We are not able to re-execute
612 // the codegen_unit query from just the DepNode, so an unknown color would
613 // lead to having to re-execute compile_codegen_unit, possibly
615 if tcx.dep_graph.is_fully_enabled() {
616 for cgu in &codegen_units {
617 tcx.codegen_unit(cgu.name().clone());
621 let ongoing_codegen = start_async_codegen(
627 codegen_units.len());
628 let ongoing_codegen = AbortCodegenOnDrop::<B>(Some(ongoing_codegen));
630 // Codegen an allocator shim, if necessary.
632 // If the crate doesn't have an `allocator_kind` set then there's definitely
633 // no shim to generate. Otherwise we also check our dependency graph for all
634 // our output crate types. If anything there looks like its a `Dynamic`
635 // linkage, then it's already got an allocator shim and we'll be using that
636 // one instead. If nothing exists then it's our job to generate the
638 let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
641 use rustc::middle::dependency_format::Linkage;
642 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
644 let allocator_module = if any_dynamic_crate {
646 } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
647 let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
649 Some("allocator")).as_str()
651 let modules = backend.new_metadata(tcx.sess, &llmod_id);
652 time(tcx.sess, "write allocator module", || {
653 backend.codegen_allocator(tcx, &modules, kind)
658 module_llvm: modules,
659 kind: ModuleKind::Allocator,
665 if let Some(allocator_module) = allocator_module {
666 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
669 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
671 // We sort the codegen units by size. This way we can schedule work for LLVM
672 // a bit more efficiently.
673 let codegen_units = {
674 let mut codegen_units = codegen_units;
675 codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
679 let mut total_codegen_time = Duration::new(0, 0);
680 let mut all_stats = Stats::default();
682 for cgu in codegen_units.into_iter() {
683 ongoing_codegen.wait_for_signal_to_codegen_item();
684 ongoing_codegen.check_for_errors(tcx.sess);
686 let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
687 tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
691 let _timing_guard = time_graph.as_ref().map(|time_graph| {
692 time_graph.start(CODEGEN_WORKER_TIMELINE,
693 CODEGEN_WORK_PACKAGE_KIND,
694 &format!("codegen {}", cgu.name()))
696 let start_time = Instant::now();
697 let stats = backend.compile_codegen_unit(tcx, *cgu.name());
698 all_stats.extend(stats);
699 total_codegen_time += start_time.elapsed();
702 CguReuse::PreLto => {
703 submit_pre_lto_module_to_llvm(&backend, tcx, CachedModuleCodegen {
704 name: cgu.name().to_string(),
705 source: cgu.work_product(tcx),
709 CguReuse::PostLto => {
710 submit_post_lto_module_to_llvm(&backend, tcx, CachedModuleCodegen {
711 name: cgu.name().to_string(),
712 source: cgu.work_product(tcx),
719 ongoing_codegen.codegen_finished(tcx);
721 // Since the main thread is sometimes blocked during codegen, we keep track
722 // -Ztime-passes output manually.
723 print_time_passes_entry(tcx.sess.time_passes(),
724 "codegen to LLVM IR",
727 ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
729 symbol_names_test::report_symbol_names(tcx);
731 if tcx.sess.codegen_stats() {
732 println!("--- codegen stats ---");
733 println!("n_glues_created: {}", all_stats.n_glues_created);
734 println!("n_null_glues: {}", all_stats.n_null_glues);
735 println!("n_real_glues: {}", all_stats.n_real_glues);
737 println!("n_fns: {}", all_stats.n_fns);
738 println!("n_inlines: {}", all_stats.n_inlines);
739 println!("n_closures: {}", all_stats.n_closures);
740 println!("fn stats:");
741 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
742 for &(ref name, insns) in all_stats.fn_stats.iter() {
743 println!("{} insns, {}", insns, *name);
747 if tcx.sess.count_llvm_insns() {
748 for (k, v) in all_stats.llvm_insns.iter() {
749 println!("{:7} {}", *v, *k);
753 ongoing_codegen.check_for_errors(tcx.sess);
755 assert_and_save_dep_graph(tcx);
756 ongoing_codegen.into_inner()
759 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
760 /// when it's dropped abnormally.
762 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
763 /// stumbled upon. The segfault was never reproduced locally, but it was
764 /// suspected to be related to the fact that codegen worker threads were
765 /// sticking around by the time the main thread was exiting, causing issues.
767 /// This structure is an attempt to fix that issue where the `codegen_aborted`
768 /// message will block until all workers have finished. This should ensure that
769 /// even if the main codegen thread panics we'll wait for pending work to
770 /// complete before returning from the main thread, hopefully avoiding
773 /// If you see this comment in the code, then it means that this workaround
774 /// worked! We may yet one day track down the mysterious cause of that
776 struct AbortCodegenOnDrop<B: ExtraBackendMethods>(Option<OngoingCodegen<B>>);
778 impl<B: ExtraBackendMethods> AbortCodegenOnDrop<B> {
779 fn into_inner(mut self) -> OngoingCodegen<B> {
780 self.0.take().unwrap()
784 impl<B: ExtraBackendMethods> Deref for AbortCodegenOnDrop<B> {
785 type Target = OngoingCodegen<B>;
787 fn deref(&self) -> &OngoingCodegen<B> {
788 self.0.as_ref().unwrap()
792 impl<B: ExtraBackendMethods> DerefMut for AbortCodegenOnDrop<B> {
793 fn deref_mut(&mut self) -> &mut OngoingCodegen<B> {
794 self.0.as_mut().unwrap()
798 impl<B: ExtraBackendMethods> Drop for AbortCodegenOnDrop<B> {
800 if let Some(codegen) = self.0.take() {
801 codegen.codegen_aborted();
806 fn assert_and_save_dep_graph<'ll, 'tcx>(tcx: TyCtxt<'ll, 'tcx, 'tcx>) {
809 || ::rustc_incremental::assert_dep_graph(tcx));
812 "serialize dep graph",
813 || ::rustc_incremental::save_dep_graph(tcx));
817 pub fn new(tcx: TyCtxt) -> CrateInfo {
818 let mut info = CrateInfo {
820 compiler_builtins: None,
821 profiler_runtime: None,
822 sanitizer_runtime: None,
823 is_no_builtins: Default::default(),
824 native_libraries: Default::default(),
825 used_libraries: tcx.native_libraries(LOCAL_CRATE),
826 link_args: tcx.link_args(LOCAL_CRATE),
827 crate_name: Default::default(),
828 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
829 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
830 used_crate_source: Default::default(),
831 wasm_imports: Default::default(),
832 lang_item_to_crate: Default::default(),
833 missing_lang_items: Default::default(),
835 let lang_items = tcx.lang_items();
837 let load_wasm_items = tcx.sess.crate_types.borrow()
839 .any(|c| *c != config::CrateType::Rlib) &&
840 tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
843 info.load_wasm_imports(tcx, LOCAL_CRATE);
846 let crates = tcx.crates();
848 let n_crates = crates.len();
849 info.native_libraries.reserve(n_crates);
850 info.crate_name.reserve(n_crates);
851 info.used_crate_source.reserve(n_crates);
852 info.missing_lang_items.reserve(n_crates);
854 for &cnum in crates.iter() {
855 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
856 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
857 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
858 if tcx.is_panic_runtime(cnum) {
859 info.panic_runtime = Some(cnum);
861 if tcx.is_compiler_builtins(cnum) {
862 info.compiler_builtins = Some(cnum);
864 if tcx.is_profiler_runtime(cnum) {
865 info.profiler_runtime = Some(cnum);
867 if tcx.is_sanitizer_runtime(cnum) {
868 info.sanitizer_runtime = Some(cnum);
870 if tcx.is_no_builtins(cnum) {
871 info.is_no_builtins.insert(cnum);
874 info.load_wasm_imports(tcx, cnum);
876 let missing = tcx.missing_lang_items(cnum);
877 for &item in missing.iter() {
878 if let Ok(id) = lang_items.require(item) {
879 info.lang_item_to_crate.insert(item, id.krate);
883 // No need to look for lang items that are whitelisted and don't
884 // actually need to exist.
885 let missing = missing.iter()
887 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
889 info.missing_lang_items.insert(cnum, missing);
895 fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
896 self.wasm_imports.extend(tcx.wasm_import_module_map(cnum).iter().map(|(&id, module)| {
897 let instance = Instance::mono(tcx, id);
898 let import_name = tcx.symbol_name(instance);
900 (import_name.to_string(), module.clone())
905 fn is_codegened_item(tcx: TyCtxt, id: DefId) -> bool {
906 let (all_mono_items, _) =
907 tcx.collect_and_partition_mono_items(LOCAL_CRATE);
908 all_mono_items.contains(&id)
911 pub fn provide_both(providers: &mut Providers) {
912 providers.dllimport_foreign_items = |tcx, krate| {
913 let module_map = tcx.foreign_modules(krate);
914 let module_map = module_map.iter()
915 .map(|lib| (lib.def_id, lib))
916 .collect::<FxHashMap<_, _>>();
918 let dllimports = tcx.native_libraries(krate)
921 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
924 let cfg = match lib.cfg {
925 Some(ref cfg) => cfg,
928 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
930 .filter_map(|lib| lib.foreign_module)
931 .map(|id| &module_map[&id])
932 .flat_map(|module| module.foreign_items.iter().cloned())
937 providers.is_dllimport_foreign_item = |tcx, def_id| {
938 tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
942 fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
943 cgu: &CodegenUnit<'tcx>)
945 if !tcx.dep_graph.is_fully_enabled() {
949 let work_product_id = &cgu.work_product_id();
950 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
951 // We don't have anything cached for this CGU. This can happen
952 // if the CGU did not exist in the previous session.
956 // Try to mark the CGU as green. If it we can do so, it means that nothing
957 // affecting the LLVM module has changed and we can re-use a cached version.
958 // If we compile with any kind of LTO, this means we can re-use the bitcode
959 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
960 // know that later). If we are not doing LTO, there is only one optimized
961 // version of each module, so we re-use that.
962 let dep_node = cgu.codegen_dep_node(tcx);
963 assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
964 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
967 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
968 // We can re-use either the pre- or the post-thinlto state
969 if tcx.sess.lto() != Lto::No {