]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_ssa/base.rs
c68694ad688ccfad82401a523581ebfa87ccde62
[rust.git] / src / librustc_codegen_ssa / base.rs
1 //! Codegen the completed AST to the LLVM IR.
2 //!
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.
7 //!
8 //! Hopefully useful general knowledge about codegen:
9 //!
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`.
15
16 use crate::back::write::{
17     start_async_codegen, submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm,
18     submit_pre_lto_module_to_llvm, OngoingCodegen,
19 };
20 use crate::common::{IntPredicate, RealPredicate, TypeKind};
21 use crate::meth;
22 use crate::mir;
23 use crate::mir::operand::OperandValue;
24 use crate::mir::place::PlaceRef;
25 use crate::traits::*;
26 use crate::{CachedModuleCodegen, CrateInfo, MemFlags, ModuleCodegen, ModuleKind};
27
28 use rustc_attr as attr;
29 use rustc_data_structures::fx::FxHashMap;
30 use rustc_data_structures::profiling::print_time_passes_entry;
31 use rustc_data_structures::sync::{par_iter, Lock, ParallelIterator};
32 use rustc_hir as hir;
33 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
34 use rustc_index::vec::Idx;
35 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
36 use rustc_middle::middle::cstore::EncodedMetadata;
37 use rustc_middle::middle::cstore::{self, LinkagePreference};
38 use rustc_middle::middle::lang_items;
39 use rustc_middle::middle::lang_items::StartFnLangItem;
40 use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem};
41 use rustc_middle::ty::layout::{self, HasTyCtxt, TyAndLayout};
42 use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
43 use rustc_middle::ty::query::Providers;
44 use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
45 use rustc_session::cgu_reuse_tracker::CguReuse;
46 use rustc_session::config::{self, EntryFnType, Lto};
47 use rustc_session::Session;
48 use rustc_span::Span;
49 use rustc_symbol_mangling::test as symbol_names_test;
50 use rustc_target::abi::{Abi, Align, LayoutOf, Scalar, VariantIdx};
51
52 use std::cmp;
53 use std::ops::{Deref, DerefMut};
54 use std::time::{Duration, Instant};
55
56 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind, signed: bool) -> IntPredicate {
57     match op {
58         hir::BinOpKind::Eq => IntPredicate::IntEQ,
59         hir::BinOpKind::Ne => IntPredicate::IntNE,
60         hir::BinOpKind::Lt => {
61             if signed {
62                 IntPredicate::IntSLT
63             } else {
64                 IntPredicate::IntULT
65             }
66         }
67         hir::BinOpKind::Le => {
68             if signed {
69                 IntPredicate::IntSLE
70             } else {
71                 IntPredicate::IntULE
72             }
73         }
74         hir::BinOpKind::Gt => {
75             if signed {
76                 IntPredicate::IntSGT
77             } else {
78                 IntPredicate::IntUGT
79             }
80         }
81         hir::BinOpKind::Ge => {
82             if signed {
83                 IntPredicate::IntSGE
84             } else {
85                 IntPredicate::IntUGE
86             }
87         }
88         op => bug!(
89             "comparison_op_to_icmp_predicate: expected comparison operator, \
90              found {:?}",
91             op
92         ),
93     }
94 }
95
96 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> RealPredicate {
97     match op {
98         hir::BinOpKind::Eq => RealPredicate::RealOEQ,
99         hir::BinOpKind::Ne => RealPredicate::RealUNE,
100         hir::BinOpKind::Lt => RealPredicate::RealOLT,
101         hir::BinOpKind::Le => RealPredicate::RealOLE,
102         hir::BinOpKind::Gt => RealPredicate::RealOGT,
103         hir::BinOpKind::Ge => RealPredicate::RealOGE,
104         op => {
105             bug!(
106                 "comparison_op_to_fcmp_predicate: expected comparison operator, \
107                  found {:?}",
108                 op
109             );
110         }
111     }
112 }
113
114 pub fn compare_simd_types<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
115     bx: &mut Bx,
116     lhs: Bx::Value,
117     rhs: Bx::Value,
118     t: Ty<'tcx>,
119     ret_ty: Bx::Type,
120     op: hir::BinOpKind,
121 ) -> Bx::Value {
122     let signed = match t.kind {
123         ty::Float(_) => {
124             let cmp = bin_op_to_fcmp_predicate(op);
125             let cmp = bx.fcmp(cmp, lhs, rhs);
126             return bx.sext(cmp, ret_ty);
127         }
128         ty::Uint(_) => false,
129         ty::Int(_) => true,
130         _ => bug!("compare_simd_types: invalid SIMD type"),
131     };
132
133     let cmp = bin_op_to_icmp_predicate(op, signed);
134     let cmp = bx.icmp(cmp, lhs, rhs);
135     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
136     // to get the correctly sized type. This will compile to a single instruction
137     // once the IR is converted to assembly if the SIMD instruction is supported
138     // by the target architecture.
139     bx.sext(cmp, ret_ty)
140 }
141
142 /// Retrieves the information we are losing (making dynamic) in an unsizing
143 /// adjustment.
144 ///
145 /// The `old_info` argument is a bit odd. It is intended for use in an upcast,
146 /// where the new vtable for an object will be derived from the old one.
147 pub fn unsized_info<'tcx, Cx: CodegenMethods<'tcx>>(
148     cx: &Cx,
149     source: Ty<'tcx>,
150     target: Ty<'tcx>,
151     old_info: Option<Cx::Value>,
152 ) -> Cx::Value {
153     let (source, target) =
154         cx.tcx().struct_lockstep_tails_erasing_lifetimes(source, target, cx.param_env());
155     match (&source.kind, &target.kind) {
156         (&ty::Array(_, len), &ty::Slice(_)) => {
157             cx.const_usize(len.eval_usize(cx.tcx(), ty::ParamEnv::reveal_all()))
158         }
159         (&ty::Dynamic(..), &ty::Dynamic(..)) => {
160             // For now, upcasts are limited to changes in marker
161             // traits, and hence never actually require an actual
162             // change to the vtable.
163             old_info.expect("unsized_info: missing old info for trait upcast")
164         }
165         (_, &ty::Dynamic(ref data, ..)) => {
166             let vtable_ptr = cx.layout_of(cx.tcx().mk_mut_ptr(target)).field(cx, FAT_PTR_EXTRA);
167             cx.const_ptrcast(
168                 meth::get_vtable(cx, source, data.principal()),
169                 cx.backend_type(vtable_ptr),
170             )
171         }
172         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}", source, target),
173     }
174 }
175
176 /// Coerces `src` to `dst_ty`. `src_ty` must be a thin pointer.
177 pub fn unsize_thin_ptr<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
178     bx: &mut Bx,
179     src: Bx::Value,
180     src_ty: Ty<'tcx>,
181     dst_ty: Ty<'tcx>,
182 ) -> (Bx::Value, Bx::Value) {
183     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
184     match (&src_ty.kind, &dst_ty.kind) {
185         (&ty::Ref(_, a, _), &ty::Ref(_, b, _))
186         | (&ty::Ref(_, a, _), &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
187         | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
188             assert!(bx.cx().type_is_sized(a));
189             let ptr_ty = bx.cx().type_ptr_to(bx.cx().backend_type(bx.cx().layout_of(b)));
190             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx(), a, b, None))
191         }
192         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
193             assert_eq!(def_a, def_b);
194
195             let src_layout = bx.cx().layout_of(src_ty);
196             let dst_layout = bx.cx().layout_of(dst_ty);
197             let mut result = None;
198             for i in 0..src_layout.fields.count() {
199                 let src_f = src_layout.field(bx.cx(), i);
200                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
201                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
202                 if src_f.is_zst() {
203                     continue;
204                 }
205                 assert_eq!(src_layout.size, src_f.size);
206
207                 let dst_f = dst_layout.field(bx.cx(), i);
208                 assert_ne!(src_f.ty, dst_f.ty);
209                 assert_eq!(result, None);
210                 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
211             }
212             let (lldata, llextra) = result.unwrap();
213             // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
214             // FIXME(eddyb) move these out of this `match` arm, so they're always
215             // applied, uniformly, no matter the source/destination types.
216             (
217                 bx.bitcast(lldata, bx.cx().scalar_pair_element_backend_type(dst_layout, 0, true)),
218                 bx.bitcast(llextra, bx.cx().scalar_pair_element_backend_type(dst_layout, 1, true)),
219             )
220         }
221         _ => bug!("unsize_thin_ptr: called on bad types"),
222     }
223 }
224
225 /// Coerces `src`, which is a reference to a value of type `src_ty`,
226 /// to a value of type `dst_ty`, and stores the result in `dst`.
227 pub fn coerce_unsized_into<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
228     bx: &mut Bx,
229     src: PlaceRef<'tcx, Bx::Value>,
230     dst: PlaceRef<'tcx, Bx::Value>,
231 ) {
232     let src_ty = src.layout.ty;
233     let dst_ty = dst.layout.ty;
234     match (&src_ty.kind, &dst_ty.kind) {
235         (&ty::Ref(..), &ty::Ref(..))
236         | (&ty::Ref(..), &ty::RawPtr(..))
237         | (&ty::RawPtr(..), &ty::RawPtr(..)) => {
238             let (base, info) = match bx.load_operand(src).val {
239                 OperandValue::Pair(base, info) => {
240                     // fat-ptr to fat-ptr unsize preserves the vtable
241                     // i.e., &'a fmt::Debug+Send => &'a fmt::Debug
242                     // So we need to pointercast the base to ensure
243                     // the types match up.
244                     // FIXME(eddyb) use `scalar_pair_element_backend_type` here,
245                     // like `unsize_thin_ptr` does.
246                     let thin_ptr = dst.layout.field(bx.cx(), FAT_PTR_ADDR);
247                     (bx.pointercast(base, bx.cx().backend_type(thin_ptr)), info)
248                 }
249                 OperandValue::Immediate(base) => unsize_thin_ptr(bx, base, src_ty, dst_ty),
250                 OperandValue::Ref(..) => bug!(),
251             };
252             OperandValue::Pair(base, info).store(bx, dst);
253         }
254
255         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
256             assert_eq!(def_a, def_b);
257
258             for i in 0..def_a.variants[VariantIdx::new(0)].fields.len() {
259                 let src_f = src.project_field(bx, i);
260                 let dst_f = dst.project_field(bx, i);
261
262                 if dst_f.layout.is_zst() {
263                     continue;
264                 }
265
266                 if src_f.layout.ty == dst_f.layout.ty {
267                     memcpy_ty(
268                         bx,
269                         dst_f.llval,
270                         dst_f.align,
271                         src_f.llval,
272                         src_f.align,
273                         src_f.layout,
274                         MemFlags::empty(),
275                     );
276                 } else {
277                     coerce_unsized_into(bx, src_f, dst_f);
278                 }
279             }
280         }
281         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}", src_ty, dst_ty,),
282     }
283 }
284
285 pub fn cast_shift_expr_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
286     bx: &mut Bx,
287     op: hir::BinOpKind,
288     lhs: Bx::Value,
289     rhs: Bx::Value,
290 ) -> Bx::Value {
291     cast_shift_rhs(bx, op, lhs, rhs)
292 }
293
294 fn cast_shift_rhs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
295     bx: &mut Bx,
296     op: hir::BinOpKind,
297     lhs: Bx::Value,
298     rhs: Bx::Value,
299 ) -> Bx::Value {
300     // Shifts may have any size int on the rhs
301     if op.is_shift() {
302         let mut rhs_llty = bx.cx().val_ty(rhs);
303         let mut lhs_llty = bx.cx().val_ty(lhs);
304         if bx.cx().type_kind(rhs_llty) == TypeKind::Vector {
305             rhs_llty = bx.cx().element_type(rhs_llty)
306         }
307         if bx.cx().type_kind(lhs_llty) == TypeKind::Vector {
308             lhs_llty = bx.cx().element_type(lhs_llty)
309         }
310         let rhs_sz = bx.cx().int_width(rhs_llty);
311         let lhs_sz = bx.cx().int_width(lhs_llty);
312         if lhs_sz < rhs_sz {
313             bx.trunc(rhs, lhs_llty)
314         } else if lhs_sz > rhs_sz {
315             // FIXME (#1877: If in the future shifting by negative
316             // values is no longer undefined then this is wrong.
317             bx.zext(rhs, lhs_llty)
318         } else {
319             rhs
320         }
321     } else {
322         rhs
323     }
324 }
325
326 /// Returns `true` if this session's target will use SEH-based unwinding.
327 ///
328 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
329 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
330 /// 64-bit MinGW) instead of "full SEH".
331 pub fn wants_msvc_seh(sess: &Session) -> bool {
332     sess.target.target.options.is_like_msvc
333 }
334
335 pub fn from_immediate<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
336     bx: &mut Bx,
337     val: Bx::Value,
338 ) -> Bx::Value {
339     if bx.cx().val_ty(val) == bx.cx().type_i1() { bx.zext(val, bx.cx().type_i8()) } else { val }
340 }
341
342 pub fn to_immediate<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
343     bx: &mut Bx,
344     val: Bx::Value,
345     layout: layout::TyAndLayout<'_>,
346 ) -> Bx::Value {
347     if let Abi::Scalar(ref scalar) = layout.abi {
348         return to_immediate_scalar(bx, val, scalar);
349     }
350     val
351 }
352
353 pub fn to_immediate_scalar<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
354     bx: &mut Bx,
355     val: Bx::Value,
356     scalar: &Scalar,
357 ) -> Bx::Value {
358     if scalar.is_bool() {
359         return bx.trunc(val, bx.cx().type_i1());
360     }
361     val
362 }
363
364 pub fn memcpy_ty<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
365     bx: &mut Bx,
366     dst: Bx::Value,
367     dst_align: Align,
368     src: Bx::Value,
369     src_align: Align,
370     layout: TyAndLayout<'tcx>,
371     flags: MemFlags,
372 ) {
373     let size = layout.size.bytes();
374     if size == 0 {
375         return;
376     }
377
378     bx.memcpy(dst, dst_align, src, src_align, bx.cx().const_usize(size), flags);
379 }
380
381 pub fn codegen_instance<'a, 'tcx: 'a, Bx: BuilderMethods<'a, 'tcx>>(
382     cx: &'a Bx::CodegenCx,
383     instance: Instance<'tcx>,
384 ) {
385     // this is an info! to allow collecting monomorphization statistics
386     // and to allow finding the last function before LLVM aborts from
387     // release builds.
388     info!("codegen_instance({})", instance);
389
390     mir::codegen_mir::<Bx>(cx, instance);
391 }
392
393 /// Creates the `main` function which will initialize the rust runtime and call
394 /// users main function.
395 pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
396     cx: &'a Bx::CodegenCx,
397 ) -> Option<Bx::Function> {
398     let (main_def_id, span) = match cx.tcx().entry_fn(LOCAL_CRATE) {
399         Some((def_id, _)) => (def_id, cx.tcx().def_span(def_id)),
400         None => return None,
401     };
402
403     let instance = Instance::mono(cx.tcx(), main_def_id);
404
405     if !cx.codegen_unit().contains_item(&MonoItem::Fn(instance)) {
406         // We want to create the wrapper in the same codegen unit as Rust's main
407         // function.
408         return None;
409     }
410
411     let main_llfn = cx.get_fn_addr(instance);
412
413     return cx.tcx().entry_fn(LOCAL_CRATE).map(|(_, et)| {
414         let use_start_lang_item = EntryFnType::Start != et;
415         create_entry_fn::<Bx>(cx, span, main_llfn, main_def_id, use_start_lang_item)
416     });
417
418     fn create_entry_fn<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
419         cx: &'a Bx::CodegenCx,
420         sp: Span,
421         rust_main: Bx::Value,
422         rust_main_def_id: DefId,
423         use_start_lang_item: bool,
424     ) -> Bx::Function {
425         // The entry function is either `int main(void)` or `int main(int argc, char **argv)`,
426         // depending on whether the target needs `argc` and `argv` to be passed in.
427         let llfty = if cx.sess().target.target.options.main_needs_argc_argv {
428             cx.type_func(&[cx.type_int(), cx.type_ptr_to(cx.type_i8p())], cx.type_int())
429         } else {
430             cx.type_func(&[], cx.type_int())
431         };
432
433         let main_ret_ty = cx.tcx().fn_sig(rust_main_def_id).output();
434         // Given that `main()` has no arguments,
435         // then its return type cannot have
436         // late-bound regions, since late-bound
437         // regions must appear in the argument
438         // listing.
439         let main_ret_ty = cx.tcx().erase_regions(&main_ret_ty.no_bound_vars().unwrap());
440
441         if cx.get_declared_value("main").is_some() {
442             // FIXME: We should be smart and show a better diagnostic here.
443             cx.sess()
444                 .struct_span_err(sp, "entry symbol `main` declared multiple times")
445                 .help("did you use `#[no_mangle]` on `fn main`? Use `#[start]` instead")
446                 .emit();
447             cx.sess().abort_if_errors();
448             bug!();
449         }
450         let llfn = cx.declare_cfn("main", llfty);
451
452         // `main` should respect same config for frame pointer elimination as rest of code
453         cx.set_frame_pointer_elimination(llfn);
454         cx.apply_target_cpu_attr(llfn);
455
456         let mut bx = Bx::new_block(&cx, llfn, "top");
457
458         bx.insert_reference_to_gdb_debug_scripts_section_global();
459
460         let (arg_argc, arg_argv) = get_argc_argv(cx, &mut bx);
461
462         let (start_fn, args) = if use_start_lang_item {
463             let start_def_id = cx.tcx().require_lang_item(StartFnLangItem, None);
464             let start_fn = cx.get_fn_addr(
465                 ty::Instance::resolve(
466                     cx.tcx(),
467                     ty::ParamEnv::reveal_all(),
468                     start_def_id,
469                     cx.tcx().intern_substs(&[main_ret_ty.into()]),
470                 )
471                 .unwrap(),
472             );
473             (
474                 start_fn,
475                 vec![bx.pointercast(rust_main, cx.type_ptr_to(cx.type_i8p())), arg_argc, arg_argv],
476             )
477         } else {
478             debug!("using user-defined start fn");
479             (rust_main, vec![arg_argc, arg_argv])
480         };
481
482         let result = bx.call(start_fn, &args, None);
483         let cast = bx.intcast(result, cx.type_int(), true);
484         bx.ret(cast);
485
486         llfn
487     }
488 }
489
490 /// Obtain the `argc` and `argv` values to pass to the rust start function.
491 fn get_argc_argv<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
492     cx: &'a Bx::CodegenCx,
493     bx: &mut Bx,
494 ) -> (Bx::Value, Bx::Value) {
495     if cx.sess().target.target.options.main_needs_argc_argv {
496         // Params from native `main()` used as args for rust start function
497         let param_argc = bx.get_param(0);
498         let param_argv = bx.get_param(1);
499         let arg_argc = bx.intcast(param_argc, cx.type_isize(), true);
500         let arg_argv = param_argv;
501         (arg_argc, arg_argv)
502     } else {
503         // The Rust start function doesn't need `argc` and `argv`, so just pass zeros.
504         let arg_argc = bx.const_int(cx.type_int(), 0);
505         let arg_argv = bx.const_null(cx.type_ptr_to(cx.type_i8p()));
506         (arg_argc, arg_argv)
507     }
508 }
509
510 pub const CODEGEN_WORKER_ID: usize = ::std::usize::MAX;
511
512 pub fn codegen_crate<B: ExtraBackendMethods>(
513     backend: B,
514     tcx: TyCtxt<'tcx>,
515     metadata: EncodedMetadata,
516     need_metadata_module: bool,
517 ) -> OngoingCodegen<B> {
518     // Skip crate items and just output metadata in -Z no-codegen mode.
519     if tcx.sess.opts.debugging_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
520         let ongoing_codegen = start_async_codegen(backend, tcx, metadata, 1);
521
522         ongoing_codegen.codegen_finished(tcx);
523
524         finalize_tcx(tcx);
525
526         ongoing_codegen.check_for_errors(tcx.sess);
527
528         return ongoing_codegen;
529     }
530
531     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
532
533     // Run the monomorphization collector and partition the collected items into
534     // codegen units.
535     let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
536     let codegen_units = (*codegen_units).clone();
537
538     // Force all codegen_unit queries so they are already either red or green
539     // when compile_codegen_unit accesses them. We are not able to re-execute
540     // the codegen_unit query from just the DepNode, so an unknown color would
541     // lead to having to re-execute compile_codegen_unit, possibly
542     // unnecessarily.
543     if tcx.dep_graph.is_fully_enabled() {
544         for cgu in &codegen_units {
545             tcx.codegen_unit(cgu.name());
546         }
547     }
548
549     let ongoing_codegen = start_async_codegen(backend.clone(), tcx, metadata, codegen_units.len());
550     let ongoing_codegen = AbortCodegenOnDrop::<B>(Some(ongoing_codegen));
551
552     // Codegen an allocator shim, if necessary.
553     //
554     // If the crate doesn't have an `allocator_kind` set then there's definitely
555     // no shim to generate. Otherwise we also check our dependency graph for all
556     // our output crate types. If anything there looks like its a `Dynamic`
557     // linkage, then it's already got an allocator shim and we'll be using that
558     // one instead. If nothing exists then it's our job to generate the
559     // allocator!
560     let any_dynamic_crate = tcx.dependency_formats(LOCAL_CRATE).iter().any(|(_, list)| {
561         use rustc_middle::middle::dependency_format::Linkage;
562         list.iter().any(|&linkage| linkage == Linkage::Dynamic)
563     });
564     let allocator_module = if any_dynamic_crate {
565         None
566     } else if let Some(kind) = tcx.allocator_kind() {
567         let llmod_id =
568             cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("allocator")).to_string();
569         let mut modules = backend.new_metadata(tcx, &llmod_id);
570         tcx.sess
571             .time("write_allocator_module", || backend.codegen_allocator(tcx, &mut modules, kind));
572
573         Some(ModuleCodegen { name: llmod_id, module_llvm: modules, kind: ModuleKind::Allocator })
574     } else {
575         None
576     };
577
578     if let Some(allocator_module) = allocator_module {
579         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
580     }
581
582     if need_metadata_module {
583         // Codegen the encoded metadata.
584         let metadata_cgu_name =
585             cgu_name_builder.build_cgu_name(LOCAL_CRATE, &["crate"], Some("metadata")).to_string();
586         let mut metadata_llvm_module = backend.new_metadata(tcx, &metadata_cgu_name);
587         tcx.sess.time("write_compressed_metadata", || {
588             backend.write_compressed_metadata(
589                 tcx,
590                 &ongoing_codegen.metadata,
591                 &mut metadata_llvm_module,
592             );
593         });
594
595         let metadata_module = ModuleCodegen {
596             name: metadata_cgu_name,
597             module_llvm: metadata_llvm_module,
598             kind: ModuleKind::Metadata,
599         };
600         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
601     }
602
603     // We sort the codegen units by size. This way we can schedule work for LLVM
604     // a bit more efficiently.
605     let codegen_units = {
606         let mut codegen_units = codegen_units;
607         codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
608         codegen_units
609     };
610
611     let total_codegen_time = Lock::new(Duration::new(0, 0));
612
613     // The non-parallel compiler can only translate codegen units to LLVM IR
614     // on a single thread, leading to a staircase effect where the N LLVM
615     // threads have to wait on the single codegen threads to generate work
616     // for them. The parallel compiler does not have this restriction, so
617     // we can pre-load the LLVM queue in parallel before handing off
618     // coordination to the OnGoingCodegen scheduler.
619     //
620     // This likely is a temporary measure. Once we don't have to support the
621     // non-parallel compiler anymore, we can compile CGUs end-to-end in
622     // parallel and get rid of the complicated scheduling logic.
623     let pre_compile_cgus = |cgu_reuse: &[CguReuse]| {
624         if cfg!(parallel_compiler) {
625             tcx.sess.time("compile_first_CGU_batch", || {
626                 // Try to find one CGU to compile per thread.
627                 let cgus: Vec<_> = cgu_reuse
628                     .iter()
629                     .enumerate()
630                     .filter(|&(_, reuse)| reuse == &CguReuse::No)
631                     .take(tcx.sess.threads())
632                     .collect();
633
634                 // Compile the found CGUs in parallel.
635                 par_iter(cgus)
636                     .map(|(i, _)| {
637                         let start_time = Instant::now();
638                         let module = backend.compile_codegen_unit(tcx, codegen_units[i].name());
639                         let mut time = total_codegen_time.lock();
640                         *time += start_time.elapsed();
641                         (i, module)
642                     })
643                     .collect()
644             })
645         } else {
646             FxHashMap::default()
647         }
648     };
649
650     let mut cgu_reuse = Vec::new();
651     let mut pre_compiled_cgus: Option<FxHashMap<usize, _>> = None;
652
653     for (i, cgu) in codegen_units.iter().enumerate() {
654         ongoing_codegen.wait_for_signal_to_codegen_item();
655         ongoing_codegen.check_for_errors(tcx.sess);
656
657         // Do some setup work in the first iteration
658         if pre_compiled_cgus.is_none() {
659             // Calculate the CGU reuse
660             cgu_reuse = tcx.sess.time("find_cgu_reuse", || {
661                 codegen_units.iter().map(|cgu| determine_cgu_reuse(tcx, &cgu)).collect()
662             });
663             // Pre compile some CGUs
664             pre_compiled_cgus = Some(pre_compile_cgus(&cgu_reuse));
665         }
666
667         let cgu_reuse = cgu_reuse[i];
668         tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
669
670         match cgu_reuse {
671             CguReuse::No => {
672                 let (module, cost) =
673                     if let Some(cgu) = pre_compiled_cgus.as_mut().unwrap().remove(&i) {
674                         cgu
675                     } else {
676                         let start_time = Instant::now();
677                         let module = backend.compile_codegen_unit(tcx, cgu.name());
678                         let mut time = total_codegen_time.lock();
679                         *time += start_time.elapsed();
680                         module
681                     };
682                 submit_codegened_module_to_llvm(
683                     &backend,
684                     &ongoing_codegen.coordinator_send,
685                     module,
686                     cost,
687                 );
688                 false
689             }
690             CguReuse::PreLto => {
691                 submit_pre_lto_module_to_llvm(
692                     &backend,
693                     tcx,
694                     &ongoing_codegen.coordinator_send,
695                     CachedModuleCodegen {
696                         name: cgu.name().to_string(),
697                         source: cgu.work_product(tcx),
698                     },
699                 );
700                 true
701             }
702             CguReuse::PostLto => {
703                 submit_post_lto_module_to_llvm(
704                     &backend,
705                     &ongoing_codegen.coordinator_send,
706                     CachedModuleCodegen {
707                         name: cgu.name().to_string(),
708                         source: cgu.work_product(tcx),
709                     },
710                 );
711                 true
712             }
713         };
714     }
715
716     ongoing_codegen.codegen_finished(tcx);
717
718     // Since the main thread is sometimes blocked during codegen, we keep track
719     // -Ztime-passes output manually.
720     print_time_passes_entry(
721         tcx.sess.time_passes(),
722         "codegen_to_LLVM_IR",
723         total_codegen_time.into_inner(),
724     );
725
726     ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
727
728     symbol_names_test::report_symbol_names(tcx);
729
730     ongoing_codegen.check_for_errors(tcx.sess);
731
732     finalize_tcx(tcx);
733
734     ongoing_codegen.into_inner()
735 }
736
737 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
738 /// when it's dropped abnormally.
739 ///
740 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
741 /// stumbled upon. The segfault was never reproduced locally, but it was
742 /// suspected to be related to the fact that codegen worker threads were
743 /// sticking around by the time the main thread was exiting, causing issues.
744 ///
745 /// This structure is an attempt to fix that issue where the `codegen_aborted`
746 /// message will block until all workers have finished. This should ensure that
747 /// even if the main codegen thread panics we'll wait for pending work to
748 /// complete before returning from the main thread, hopefully avoiding
749 /// segfaults.
750 ///
751 /// If you see this comment in the code, then it means that this workaround
752 /// worked! We may yet one day track down the mysterious cause of that
753 /// segfault...
754 struct AbortCodegenOnDrop<B: ExtraBackendMethods>(Option<OngoingCodegen<B>>);
755
756 impl<B: ExtraBackendMethods> AbortCodegenOnDrop<B> {
757     fn into_inner(mut self) -> OngoingCodegen<B> {
758         self.0.take().unwrap()
759     }
760 }
761
762 impl<B: ExtraBackendMethods> Deref for AbortCodegenOnDrop<B> {
763     type Target = OngoingCodegen<B>;
764
765     fn deref(&self) -> &OngoingCodegen<B> {
766         self.0.as_ref().unwrap()
767     }
768 }
769
770 impl<B: ExtraBackendMethods> DerefMut for AbortCodegenOnDrop<B> {
771     fn deref_mut(&mut self) -> &mut OngoingCodegen<B> {
772         self.0.as_mut().unwrap()
773     }
774 }
775
776 impl<B: ExtraBackendMethods> Drop for AbortCodegenOnDrop<B> {
777     fn drop(&mut self) {
778         if let Some(codegen) = self.0.take() {
779             codegen.codegen_aborted();
780         }
781     }
782 }
783
784 fn finalize_tcx(tcx: TyCtxt<'_>) {
785     tcx.sess.time("assert_dep_graph", || ::rustc_incremental::assert_dep_graph(tcx));
786     tcx.sess.time("serialize_dep_graph", || ::rustc_incremental::save_dep_graph(tcx));
787
788     // We assume that no queries are run past here. If there are new queries
789     // after this point, they'll show up as "<unknown>" in self-profiling data.
790     {
791         let _prof_timer = tcx.prof.generic_activity("self_profile_alloc_query_strings");
792         tcx.alloc_self_profile_query_strings();
793     }
794 }
795
796 impl CrateInfo {
797     pub fn new(tcx: TyCtxt<'_>) -> CrateInfo {
798         let mut info = CrateInfo {
799             panic_runtime: None,
800             compiler_builtins: None,
801             profiler_runtime: None,
802             is_no_builtins: Default::default(),
803             native_libraries: Default::default(),
804             used_libraries: tcx.native_libraries(LOCAL_CRATE),
805             link_args: tcx.link_args(LOCAL_CRATE),
806             crate_name: Default::default(),
807             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
808             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
809             used_crate_source: Default::default(),
810             lang_item_to_crate: Default::default(),
811             missing_lang_items: Default::default(),
812             dependency_formats: tcx.dependency_formats(LOCAL_CRATE),
813         };
814         let lang_items = tcx.lang_items();
815
816         let crates = tcx.crates();
817
818         let n_crates = crates.len();
819         info.native_libraries.reserve(n_crates);
820         info.crate_name.reserve(n_crates);
821         info.used_crate_source.reserve(n_crates);
822         info.missing_lang_items.reserve(n_crates);
823
824         for &cnum in crates.iter() {
825             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
826             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
827             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
828             if tcx.is_panic_runtime(cnum) {
829                 info.panic_runtime = Some(cnum);
830             }
831             if tcx.is_compiler_builtins(cnum) {
832                 info.compiler_builtins = Some(cnum);
833             }
834             if tcx.is_profiler_runtime(cnum) {
835                 info.profiler_runtime = Some(cnum);
836             }
837             if tcx.is_no_builtins(cnum) {
838                 info.is_no_builtins.insert(cnum);
839             }
840             let missing = tcx.missing_lang_items(cnum);
841             for &item in missing.iter() {
842                 if let Ok(id) = lang_items.require(item) {
843                     info.lang_item_to_crate.insert(item, id.krate);
844                 }
845             }
846
847             // No need to look for lang items that are whitelisted and don't
848             // actually need to exist.
849             let missing =
850                 missing.iter().cloned().filter(|&l| !lang_items::whitelisted(tcx, l)).collect();
851             info.missing_lang_items.insert(cnum, missing);
852         }
853
854         info
855     }
856 }
857
858 pub fn provide_both(providers: &mut Providers<'_>) {
859     providers.backend_optimization_level = |tcx, cratenum| {
860         let for_speed = match tcx.sess.opts.optimize {
861             // If globally no optimisation is done, #[optimize] has no effect.
862             //
863             // This is done because if we ended up "upgrading" to `-O2` here, we’d populate the
864             // pass manager and it is likely that some module-wide passes (such as inliner or
865             // cross-function constant propagation) would ignore the `optnone` annotation we put
866             // on the functions, thus necessarily involving these functions into optimisations.
867             config::OptLevel::No => return config::OptLevel::No,
868             // If globally optimise-speed is already specified, just use that level.
869             config::OptLevel::Less => return config::OptLevel::Less,
870             config::OptLevel::Default => return config::OptLevel::Default,
871             config::OptLevel::Aggressive => return config::OptLevel::Aggressive,
872             // If globally optimize-for-size has been requested, use -O2 instead (if optimize(size)
873             // are present).
874             config::OptLevel::Size => config::OptLevel::Default,
875             config::OptLevel::SizeMin => config::OptLevel::Default,
876         };
877
878         let (defids, _) = tcx.collect_and_partition_mono_items(cratenum);
879         for id in &*defids {
880             let CodegenFnAttrs { optimize, .. } = tcx.codegen_fn_attrs(*id);
881             match optimize {
882                 attr::OptimizeAttr::None => continue,
883                 attr::OptimizeAttr::Size => continue,
884                 attr::OptimizeAttr::Speed => {
885                     return for_speed;
886                 }
887             }
888         }
889         tcx.sess.opts.optimize
890     };
891
892     providers.dllimport_foreign_items = |tcx, krate| {
893         let module_map = tcx.foreign_modules(krate);
894         let module_map =
895             module_map.iter().map(|lib| (lib.def_id, lib)).collect::<FxHashMap<_, _>>();
896
897         let dllimports = tcx
898             .native_libraries(krate)
899             .iter()
900             .filter(|lib| {
901                 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
902                     return false;
903                 }
904                 let cfg = match lib.cfg {
905                     Some(ref cfg) => cfg,
906                     None => return true,
907                 };
908                 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
909             })
910             .filter_map(|lib| lib.foreign_module)
911             .map(|id| &module_map[&id])
912             .flat_map(|module| module.foreign_items.iter().cloned())
913             .collect();
914         tcx.arena.alloc(dllimports)
915     };
916
917     providers.is_dllimport_foreign_item =
918         |tcx, def_id| tcx.dllimport_foreign_items(def_id.krate).contains(&def_id);
919 }
920
921 fn determine_cgu_reuse<'tcx>(tcx: TyCtxt<'tcx>, cgu: &CodegenUnit<'tcx>) -> CguReuse {
922     if !tcx.dep_graph.is_fully_enabled() {
923         return CguReuse::No;
924     }
925
926     let work_product_id = &cgu.work_product_id();
927     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
928         // We don't have anything cached for this CGU. This can happen
929         // if the CGU did not exist in the previous session.
930         return CguReuse::No;
931     }
932
933     // Try to mark the CGU as green. If it we can do so, it means that nothing
934     // affecting the LLVM module has changed and we can re-use a cached version.
935     // If we compile with any kind of LTO, this means we can re-use the bitcode
936     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
937     // know that later). If we are not doing LTO, there is only one optimized
938     // version of each module, so we re-use that.
939     let dep_node = cgu.codegen_dep_node(tcx);
940     assert!(
941         !tcx.dep_graph.dep_node_exists(&dep_node),
942         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
943         cgu.name()
944     );
945
946     if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
947         // We can re-use either the pre- or the post-thinlto state
948         if tcx.sess.lto() != Lto::No { CguReuse::PreLto } else { CguReuse::PostLto }
949     } else {
950         CguReuse::No
951     }
952 }