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