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