1 //! Codegen the completed AST to the LLVM IR.
3 //! Some functions here, such as codegen_block and codegen_expr, return a value --
4 //! the result of the codegen to LLVM -- while others, such as codegen_fn
5 //! and mono_item, are called only for the side effect of adding a
6 //! particular definition to the LLVM IR output we're producing.
8 //! Hopefully useful general knowledge about codegen:
10 //! * There's no way to find out the `Ty` type of a Value. Doing so
11 //! would be "trying to get the eggs out of an omelette" (credit:
12 //! pcwalton). You can, instead, find out its `llvm::Type` by calling `val_ty`,
13 //! but one `llvm::Type` corresponds to many `Ty`s; for instance, `tup(int, int,
14 //! int)` and `rec(x=int, y=int, z=int)` will have the same `llvm::Type`.
16 use crate::{ModuleCodegen, ModuleKind, CachedModuleCodegen};
18 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
19 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
20 use rustc::middle::cstore::EncodedMetadata;
21 use rustc::middle::lang_items::StartFnLangItem;
22 use rustc::middle::weak_lang_items;
23 use rustc::mir::mono::{Stats, CodegenUnitNameBuilder};
24 use rustc::ty::{self, Ty, TyCtxt};
25 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf, VariantIdx, HasTyCtxt};
26 use rustc::ty::query::Providers;
27 use rustc::middle::cstore::{self, LinkagePreference};
28 use rustc::util::common::{time, print_time_passes_entry};
29 use rustc::session::config::{self, EntryFnType, Lto};
30 use rustc::session::Session;
31 use rustc_mir::monomorphize::item::DefPathBasedNames;
32 use rustc_mir::monomorphize::Instance;
33 use rustc_mir::monomorphize::partitioning::{CodegenUnit, CodegenUnitExt};
34 use rustc::util::nodemap::FxHashMap;
35 use rustc_data_structures::indexed_vec::Idx;
36 use rustc_codegen_utils::{symbol_names_test, check_for_rustc_errors_attr};
37 use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
38 use crate::mir::place::PlaceRef;
39 use crate::back::write::{OngoingCodegen, start_async_codegen, submit_pre_lto_module_to_llvm,
40 submit_post_lto_module_to_llvm};
41 use crate::{MemFlags, CrateInfo};
43 use crate::common::{RealPredicate, TypeKind, IntPredicate};
46 use crate::mono_item::MonoItem;
52 use std::ops::{Deref, DerefMut};
53 use std::time::{Instant, Duration};
59 use crate::mir::operand::OperandValue;
61 use std::marker::PhantomData;
63 pub struct StatRecorder<'a, 'tcx, Cx: 'a + CodegenMethods<'tcx>> {
67 _marker: PhantomData<&'tcx ()>,
70 impl<'a, 'tcx, Cx: CodegenMethods<'tcx>> StatRecorder<'a, 'tcx, Cx> {
71 pub fn new(cx: &'a Cx, name: String) -> Self {
72 let istart = cx.stats().borrow().n_llvm_insns;
82 impl<'a, 'tcx, Cx: CodegenMethods<'tcx>> Drop for StatRecorder<'a, 'tcx, Cx> {
84 if self.cx.sess().codegen_stats() {
85 let mut stats = self.cx.stats().borrow_mut();
86 let iend = stats.n_llvm_insns;
87 stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
89 // Reset LLVM insn count to avoid compound costs.
90 stats.n_llvm_insns = self.istart;
95 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
99 hir::BinOpKind::Eq => IntPredicate::IntEQ,
100 hir::BinOpKind::Ne => IntPredicate::IntNE,
101 hir::BinOpKind::Lt => if signed { IntPredicate::IntSLT } else { IntPredicate::IntULT },
102 hir::BinOpKind::Le => if signed { IntPredicate::IntSLE } else { IntPredicate::IntULE },
103 hir::BinOpKind::Gt => if signed { IntPredicate::IntSGT } else { IntPredicate::IntUGT },
104 hir::BinOpKind::Ge => if signed { IntPredicate::IntSGE } else { IntPredicate::IntUGE },
106 bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
113 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
115 hir::BinOpKind::Eq => RealPredicate::RealOEQ,
116 hir::BinOpKind::Ne => RealPredicate::RealUNE,
117 hir::BinOpKind::Lt => RealPredicate::RealOLT,
118 hir::BinOpKind::Le => RealPredicate::RealOLE,
119 hir::BinOpKind::Gt => RealPredicate::RealOGT,
120 hir::BinOpKind::Ge => RealPredicate::RealOGE,
122 bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
129 pub fn compare_simd_types<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
137 let signed = match t.sty {
139 let cmp = bin_op_to_fcmp_predicate(op);
140 let cmp = bx.fcmp(cmp, lhs, rhs);
141 return bx.sext(cmp, ret_ty);
143 ty::Uint(_) => false,
145 _ => bug!("compare_simd_types: invalid SIMD type"),
148 let cmp = bin_op_to_icmp_predicate(op, signed);
149 let cmp = bx.icmp(cmp, lhs, rhs);
150 // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
151 // to get the correctly sized type. This will compile to a single instruction
152 // once the IR is converted to assembly if the SIMD instruction is supported
153 // by the target architecture.
157 /// Retrieves the information we are losing (making dynamic) in an unsizing
160 /// The `old_info` argument is a bit funny. It is intended for use
161 /// in an upcast, where the new vtable for an object will be derived
162 /// from the old one.
163 pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>(
167 old_info: Option<Cx::Value>,
169 let (source, target) = cx.tcx().struct_lockstep_tails(source, target);
170 match (&source.sty, &target.sty) {
171 (&ty::Array(_, len), &ty::Slice(_)) => {
172 cx.const_usize(len.unwrap_usize(cx.tcx()))
174 (&ty::Dynamic(..), &ty::Dynamic(..)) => {
175 // For now, upcasts are limited to changes in marker
176 // traits, and hence never actually require an actual
177 // change to the vtable.
178 old_info.expect("unsized_info: missing old info for trait upcast")
180 (_, &ty::Dynamic(ref data, ..)) => {
181 let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target))
182 .field(cx, FAT_PTR_EXTRA);
183 cx.const_ptrcast(meth::get_vtable(cx, source, data.principal()),
184 cx.backend_type(vtable_ptr))
186 _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
192 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
193 pub fn unsize_thin_ptr<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
198 ) -> (Bx::Value, Bx::Value) {
199 debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
200 match (&src_ty.sty, &dst_ty.sty) {
204 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
205 (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
206 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
207 assert!(bx.cx().type_is_sized(a));
208 let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
209 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
211 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
212 let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
213 assert!(bx.cx().type_is_sized(a));
214 let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
215 (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
217 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
218 assert_eq!(def_a, def_b);
220 let src_layout = bx.cx().layout_of(src_ty);
221 let dst_layout = bx.cx().layout_of(dst_ty);
222 let mut result = None;
223 for i in 0..src_layout.fields.count() {
224 let src_f = src_layout.field(bx.cx(), i);
225 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
226 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
230 assert_eq!(src_layout.size, src_f.size);
232 let dst_f = dst_layout.field(bx.cx(), i);
233 assert_ne!(src_f.ty, dst_f.ty);
234 assert_eq!(result, None);
235 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
237 let (lldata, llextra) = result.unwrap();
238 // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
239 (bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)),
240 bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true)))
242 _ => bug!("unsize_thin_ptr: called on bad types"),
246 /// Coerce `src`, which is a reference to a value of type `src_ty`,
247 /// to a value of type `dst_ty` and store the result in `dst`
248 pub fn coerce_unsized_into<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
250 src: PlaceRef<'tcx, Bx::Value>,
251 dst: PlaceRef<'tcx, Bx::Value>
253 let src_ty = src.layout.ty;
254 let dst_ty = dst.layout.ty;
255 let mut coerce_ptr = || {
256 let (base, info) = match bx.load_operand(src).val {
257 OperandValue::Pair(base, info) => {
258 // fat-ptr to fat-ptr unsize preserves the vtable
259 // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
260 // So we need to pointercast the base to ensure
261 // the types match up.
262 let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR);
263 (bx.pointercast(base, bx.cx().backend_type(thin_ptr)), info)
265 OperandValue::Immediate(base) => {
266 unsize_thin_ptr(bx, base, src_ty, dst_ty)
268 OperandValue::Ref(..) => bug!()
270 OperandValue::Pair(base, info).store(bx, dst);
272 match (&src_ty.sty, &dst_ty.sty) {
273 (&ty::Ref(..), &ty::Ref(..)) |
274 (&ty::Ref(..), &ty::RawPtr(..)) |
275 (&ty::RawPtr(..), &ty::RawPtr(..)) => {
278 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
282 (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
283 assert_eq!(def_a, def_b);
285 for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
286 let src_f = src.project_field(bx, i);
287 let dst_f = dst.project_field(bx, i);
289 if dst_f.layout.is_zst() {
293 if src_f.layout.ty == dst_f.layout.ty {
294 memcpy_ty(bx, dst_f.llval, dst_f.align, src_f.llval, src_f.align,
295 src_f.layout, MemFlags::empty());
297 coerce_unsized_into(bx, src_f, dst_f);
301 _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
307 pub fn cast_shift_expr_rhs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
313 cast_shift_rhs(bx, op, lhs, rhs)
316 fn cast_shift_rhs<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
322 // Shifts may have any size int on the rhs
324 let mut rhs_llty = bx.cx().val_ty(rhs);
325 let mut lhs_llty = bx.cx().val_ty(lhs);
326 if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
327 rhs_llty = bx.cx().element_type(rhs_llty)
329 if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
330 lhs_llty = bx.cx().element_type(lhs_llty)
332 let rhs_sz = bx.cx().int_width(rhs_llty);
333 let lhs_sz = bx.cx().int_width(lhs_llty);
335 bx.trunc(rhs, lhs_llty)
336 } else if lhs_sz > rhs_sz {
337 // FIXME (#1877: If in the future shifting by negative
338 // values is no longer undefined then this is wrong.
339 bx.zext(rhs, lhs_llty)
348 /// Returns `true` if this session's target will use SEH-based unwinding.
350 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
351 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
352 /// 64-bit MinGW) instead of "full SEH".
353 pub fn wants_msvc_seh(sess: &Session) -> bool {
354 sess.target.target.options.is_like_msvc
357 pub fn from_immediate<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
361 if bx.cx().val_ty(val) == bx.cx().type_i1() {
362 bx.zext(val, bx.cx().type_i8())
368 pub fn to_immediate<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
371 layout: layout::TyLayout<'_>,
373 if let layout::Abi::Scalar(ref scalar) = layout.abi {
374 return to_immediate_scalar(bx, val, scalar);
379 pub fn to_immediate_scalar<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
382 scalar: &layout::Scalar,
384 if scalar.is_bool() {
385 return bx.trunc(val, bx.cx().type_i1());
390 pub fn memcpy_ty<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
396 layout: TyLayout<'tcx>,
399 let size = layout.size.bytes();
404 bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
407 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
408 cx: &'a Bx::CodegenCx,
409 instance: Instance<'tcx>,
411 let _s = if cx.sess().codegen_stats() {
412 let mut instance_name = String::new();
413 DefPathBasedNames::new(cx.tcx(), true, true)
414 .push_def_path(instance.def_id(), &mut instance_name);
415 Some(StatRecorder::new(cx, instance_name))
420 // this is an info! to allow collecting monomorphization statistics
421 // and to allow finding the last function before LLVM aborts from
423 info!("codegen_instance({})", instance);
425 let sig = instance.fn_sig(cx.tcx());
426 let sig = cx.tcx().normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
428 let lldecl = cx.instances().borrow().get(&instance).cloned().unwrap_or_else(||
429 bug!("Instance `{:?}` not already declared", instance));
431 cx.stats().borrow_mut().n_closures += 1;
433 let mir = cx.tcx().instance_mir(instance.def);
434 mir::codegen_mir::<Bx>(cx, lldecl, &mir, instance, sig);
437 /// Creates the `main` function which will initialize the rust runtime and call
438 /// users main function.
439 pub fn maybe_create_entry_wrapper<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
440 cx: &'a Bx::CodegenCx
442 let (main_def_id, span) = match cx.tcx().entry_fn(LOCAL_CRATE) {
443 Some((def_id, _)) => { (def_id, cx.tcx().def_span(def_id)) },
447 let instance = Instance::mono(cx.tcx(), main_def_id);
449 if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
450 // We want to create the wrapper in the same codegen unit as Rust's main
455 let main_llfn = cx.get_fn(instance);
457 let et = cx.tcx().entry_fn(LOCAL_CRATE).map(|e| e.1);
459 Some(EntryFnType::Main) => create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, true),
460 Some(EntryFnType::Start) => create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, false),
461 None => {} // Do nothing.
464 fn create_entry_fn<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
465 cx: &'a Bx::CodegenCx,
467 rust_main: Bx::Value,
468 rust_main_def_id: DefId,
469 use_start_lang_item: bool,
472 cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int());
474 let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
475 // Given that `main()` has no arguments,
476 // then its return type cannot have
477 // late-bound regions, since late-bound
478 // regions must appear in the argument
480 let main_ret_ty = cx.tcx().erase_regions(
481 &main_ret_ty.no_bound_vars().unwrap(),
484 if cx.get_defined_value("main").is_some() {
485 // FIXME: We should be smart and show a better diagnostic here.
486 cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
487 .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
489 cx.sess().abort_if_errors();
492 let llfn = cx.declare_cfn("main", llfty);
494 // `main` should respect same config for frame pointer elimination as rest of code
495 cx.set_frame_pointer_elimination(llfn);
496 cx.apply_target_cpu_attr(llfn);
498 let mut bx = Bx::new_block(&cx, llfn, "top");
500 bx.insert_reference_to_gdb_debug_scripts_section_global();
502 // Params from native main() used as args for rust start function
503 let param_argc = bx.get_param(0);
504 let param_argv = bx.get_param(1);
505 let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
506 let arg_argv = param_argv;
508 let (start_fn, args) = if use_start_lang_item {
509 let start_def_id = cx.tcx().require_lang_item(StartFnLangItem);
510 let start_fn = callee::resolve_and_get_fn(
513 cx.tcx().intern_substs(&[main_ret_ty.into()]),
515 (start_fn, vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())),
518 debug!("using user-defined start fn");
519 (rust_main, vec![arg_argc, arg_argv])
522 let result = bx.call(start_fn, &args, None);
523 let cast = bx.intcast(result, cx.type_int(), true);
528 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
530 pub fn codegen_crate<B: ExtraBackendMethods>(
532 tcx: TyCtxt<'a, 'tcx, 'tcx>,
533 metadata: EncodedMetadata,
534 need_metadata_module: bool,
535 rx: mpsc::Receiver<Box<dyn Any + Send>>
536 ) -> OngoingCodegen<B> {
538 check_for_rustc_errors_attr(tcx);
540 // Skip crate items and just output metadata in -Z no-codegen mode.
541 if tcx.sess.opts.debugging_opts.no_codegen ||
542 !tcx.sess.opts.output_types.should_codegen() {
543 let ongoing_codegen = start_async_codegen(
550 ongoing_codegen.codegen_finished(tcx);
552 assert_and_save_dep_graph(tcx);
554 ongoing_codegen.check_for_errors(tcx.sess);
556 return ongoing_codegen;
559 let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
561 // Run the monomorphization collector and partition the collected items into
563 let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
564 let codegen_units = (*codegen_units).clone();
566 // Force all codegen_unit queries so they are already either red or green
567 // when compile_codegen_unit accesses them. We are not able to re-execute
568 // the codegen_unit query from just the DepNode, so an unknown color would
569 // lead to having to re-execute compile_codegen_unit, possibly
571 if tcx.dep_graph.is_fully_enabled() {
572 for cgu in &codegen_units {
573 tcx.codegen_unit(cgu.name().clone());
577 let ongoing_codegen = start_async_codegen(
582 codegen_units.len());
583 let ongoing_codegen = AbortCodegenOnDrop::<B>(Some(ongoing_codegen));
585 // Codegen an allocator shim, if necessary.
587 // If the crate doesn't have an `allocator_kind` set then there's definitely
588 // no shim to generate. Otherwise we also check our dependency graph for all
589 // our output crate types. If anything there looks like its a `Dynamic`
590 // linkage, then it's already got an allocator shim and we'll be using that
591 // one instead. If nothing exists then it's our job to generate the
593 let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
596 use rustc::middle::dependency_format::Linkage;
597 list.iter().any(|&linkage| linkage == Linkage::Dynamic)
599 let allocator_module = if any_dynamic_crate {
601 } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
602 let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
604 Some("allocator")).as_str()
606 let mut modules = backend.new_metadata(tcx, &llmod_id);
607 time(tcx.sess, "write allocator module", || {
608 backend.codegen_allocator(tcx, &mut modules, kind)
613 module_llvm: modules,
614 kind: ModuleKind::Allocator,
620 if let Some(allocator_module) = allocator_module {
621 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
624 if need_metadata_module {
625 // Codegen the encoded metadata.
626 tcx.sess.profiler(|p| p.start_activity("codegen crate metadata"));
628 let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
630 Some("metadata")).as_str()
632 let mut metadata_llvm_module = backend.new_metadata(tcx, &metadata_cgu_name);
633 time(tcx.sess, "write compressed metadata", || {
634 backend.write_compressed_metadata(tcx, &ongoing_codegen.metadata,
635 &mut metadata_llvm_module);
637 tcx.sess.profiler(|p| p.end_activity("codegen crate metadata"));
639 let metadata_module = ModuleCodegen {
640 name: metadata_cgu_name,
641 module_llvm: metadata_llvm_module,
642 kind: ModuleKind::Metadata,
644 ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
647 // We sort the codegen units by size. This way we can schedule work for LLVM
648 // a bit more efficiently.
649 let codegen_units = {
650 let mut codegen_units = codegen_units;
651 codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
655 let mut total_codegen_time = Duration::new(0, 0);
656 let mut all_stats = Stats::default();
658 for cgu in codegen_units.into_iter() {
659 ongoing_codegen.wait_for_signal_to_codegen_item();
660 ongoing_codegen.check_for_errors(tcx.sess);
662 let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
663 tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
667 tcx.sess.profiler(|p| p.start_activity(format!("codegen {}", cgu.name())));
668 let start_time = Instant::now();
669 let stats = backend.compile_codegen_unit(tcx, *cgu.name());
670 all_stats.extend(stats);
671 total_codegen_time += start_time.elapsed();
672 tcx.sess.profiler(|p| p.end_activity(format!("codegen {}", cgu.name())));
675 CguReuse::PreLto => {
676 submit_pre_lto_module_to_llvm(&backend, tcx, CachedModuleCodegen {
677 name: cgu.name().to_string(),
678 source: cgu.work_product(tcx),
682 CguReuse::PostLto => {
683 submit_post_lto_module_to_llvm(&backend, tcx, CachedModuleCodegen {
684 name: cgu.name().to_string(),
685 source: cgu.work_product(tcx),
692 ongoing_codegen.codegen_finished(tcx);
694 // Since the main thread is sometimes blocked during codegen, we keep track
695 // -Ztime-passes output manually.
696 print_time_passes_entry(tcx.sess.time_passes(),
697 "codegen to LLVM IR",
700 ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
702 symbol_names_test::report_symbol_names(tcx);
704 if tcx.sess.codegen_stats() {
705 println!("--- codegen stats ---");
706 println!("n_glues_created: {}", all_stats.n_glues_created);
707 println!("n_null_glues: {}", all_stats.n_null_glues);
708 println!("n_real_glues: {}", all_stats.n_real_glues);
710 println!("n_fns: {}", all_stats.n_fns);
711 println!("n_inlines: {}", all_stats.n_inlines);
712 println!("n_closures: {}", all_stats.n_closures);
713 println!("fn stats:");
714 all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
715 for &(ref name, insns) in all_stats.fn_stats.iter() {
716 println!("{} insns, {}", insns, *name);
720 if tcx.sess.count_llvm_insns() {
721 for (k, v) in all_stats.llvm_insns.iter() {
722 println!("{:7} {}", *v, *k);
726 ongoing_codegen.check_for_errors(tcx.sess);
728 assert_and_save_dep_graph(tcx);
729 ongoing_codegen.into_inner()
732 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
733 /// when it's dropped abnormally.
735 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
736 /// stumbled upon. The segfault was never reproduced locally, but it was
737 /// suspected to be related to the fact that codegen worker threads were
738 /// sticking around by the time the main thread was exiting, causing issues.
740 /// This structure is an attempt to fix that issue where the `codegen_aborted`
741 /// message will block until all workers have finished. This should ensure that
742 /// even if the main codegen thread panics we'll wait for pending work to
743 /// complete before returning from the main thread, hopefully avoiding
746 /// If you see this comment in the code, then it means that this workaround
747 /// worked! We may yet one day track down the mysterious cause of that
749 struct AbortCodegenOnDrop<B: ExtraBackendMethods>(Option<OngoingCodegen<B>>);
751 impl<B: ExtraBackendMethods> AbortCodegenOnDrop<B> {
752 fn into_inner(mut self) -> OngoingCodegen<B> {
753 self.0.take().unwrap()
757 impl<B: ExtraBackendMethods> Deref for AbortCodegenOnDrop<B> {
758 type Target = OngoingCodegen<B>;
760 fn deref(&self) -> &OngoingCodegen<B> {
761 self.0.as_ref().unwrap()
765 impl<B: ExtraBackendMethods> DerefMut for AbortCodegenOnDrop<B> {
766 fn deref_mut(&mut self) -> &mut OngoingCodegen<B> {
767 self.0.as_mut().unwrap()
771 impl<B: ExtraBackendMethods> Drop for AbortCodegenOnDrop<B> {
773 if let Some(codegen) = self.0.take() {
774 codegen.codegen_aborted();
779 fn assert_and_save_dep_graph<'ll, 'tcx>(tcx: TyCtxt<'ll, 'tcx, 'tcx>) {
782 || ::rustc_incremental::assert_dep_graph(tcx));
785 "serialize dep graph",
786 || ::rustc_incremental::save_dep_graph(tcx));
790 pub fn new(tcx: TyCtxt<'_, '_, '_>) -> CrateInfo {
791 let mut info = CrateInfo {
793 compiler_builtins: None,
794 profiler_runtime: None,
795 sanitizer_runtime: None,
796 is_no_builtins: Default::default(),
797 native_libraries: Default::default(),
798 used_libraries: tcx.native_libraries(LOCAL_CRATE),
799 link_args: tcx.link_args(LOCAL_CRATE),
800 crate_name: Default::default(),
801 used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
802 used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
803 used_crate_source: Default::default(),
804 lang_item_to_crate: Default::default(),
805 missing_lang_items: Default::default(),
807 let lang_items = tcx.lang_items();
809 let crates = tcx.crates();
811 let n_crates = crates.len();
812 info.native_libraries.reserve(n_crates);
813 info.crate_name.reserve(n_crates);
814 info.used_crate_source.reserve(n_crates);
815 info.missing_lang_items.reserve(n_crates);
817 for &cnum in crates.iter() {
818 info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
819 info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
820 info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
821 if tcx.is_panic_runtime(cnum) {
822 info.panic_runtime = Some(cnum);
824 if tcx.is_compiler_builtins(cnum) {
825 info.compiler_builtins = Some(cnum);
827 if tcx.is_profiler_runtime(cnum) {
828 info.profiler_runtime = Some(cnum);
830 if tcx.is_sanitizer_runtime(cnum) {
831 info.sanitizer_runtime = Some(cnum);
833 if tcx.is_no_builtins(cnum) {
834 info.is_no_builtins.insert(cnum);
836 let missing = tcx.missing_lang_items(cnum);
837 for &item in missing.iter() {
838 if let Ok(id) = lang_items.require(item) {
839 info.lang_item_to_crate.insert(item, id.krate);
843 // No need to look for lang items that are whitelisted and don't
844 // actually need to exist.
845 let missing = missing.iter()
847 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
849 info.missing_lang_items.insert(cnum, missing);
856 fn is_codegened_item(tcx: TyCtxt<'_, '_, '_>, id: DefId) -> bool {
857 let (all_mono_items, _) =
858 tcx.collect_and_partition_mono_items(LOCAL_CRATE);
859 all_mono_items.contains(&id)
862 pub fn provide_both(providers: &mut Providers<'_>) {
863 providers.backend_optimization_level = |tcx, cratenum| {
864 let for_speed = match tcx.sess.opts.optimize {
865 // If globally no optimisation is done, #[optimize] has no effect.
867 // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
868 // pass manager and it is likely that some module-wide passes (such as inliner or
869 // cross-function constant propagation) would ignore the `optnone` annotation we put
870 // on the functions, thus necessarily involving these functions into optimisations.
871 config::OptLevel::No => return config::OptLevel::No,
872 // If globally optimise-speed is already specified, just use that level.
873 config::OptLevel::Less => return config::OptLevel::Less,
874 config::OptLevel::Default => return config::OptLevel::Default,
875 config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
876 // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
878 config::OptLevel::Size => config::OptLevel::Default,
879 config::OptLevel::SizeMin => config::OptLevel::Default,
882 let (defids, _) = tcx.collect_and_partition_mono_items(cratenum);
884 let hir::CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
886 attr::OptimizeAttr::None => continue,
887 attr::OptimizeAttr::Size => continue,
888 attr::OptimizeAttr::Speed => {
893 return tcx.sess.opts.optimize;
896 providers.dllimport_foreign_items = |tcx, krate| {
897 let module_map = tcx.foreign_modules(krate);
898 let module_map = module_map.iter()
899 .map(|lib| (lib.def_id, lib))
900 .collect::<FxHashMap<_, _>>();
902 let dllimports = tcx.native_libraries(krate)
905 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
908 let cfg = match lib.cfg {
909 Some(ref cfg) => cfg,
912 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
914 .filter_map(|lib| lib.foreign_module)
915 .map(|id| &module_map[&id])
916 .flat_map(|module| module.foreign_items.iter().cloned())
918 tcx.arena.alloc(dllimports)
921 providers.is_dllimport_foreign_item = |tcx, def_id| {
922 tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
926 fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
927 cgu: &CodegenUnit<'tcx>)
929 if !tcx.dep_graph.is_fully_enabled() {
933 let work_product_id = &cgu.work_product_id();
934 if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
935 // We don't have anything cached for this CGU. This can happen
936 // if the CGU did not exist in the previous session.
940 // Try to mark the CGU as green. If it we can do so, it means that nothing
941 // affecting the LLVM module has changed and we can re-use a cached version.
942 // If we compile with any kind of LTO, this means we can re-use the bitcode
943 // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
944 // know that later). If we are not doing LTO, there is only one optimized
945 // version of each module, so we re-use that.
946 let dep_node = cgu.codegen_dep_node(tcx);
947 assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
948 "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
951 if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
952 // We can re-use either the pre- or the post-thinlto state
953 if tcx.sess.lto() != Lto::No {