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