]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/base.rs
Rollup merge of #55136 - GuillaumeGomez:short-doc, r=QuietMisdreavus
[rust.git] / src / librustc_codegen_llvm / base.rs
1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Codegen the completed AST to the LLVM IR.
12 //!
13 //! Some functions here, such as codegen_block and codegen_expr, return a value --
14 //! the result of the codegen to LLVM -- while others, such as codegen_fn
15 //! and mono_item, are called only for the side effect of adding a
16 //! particular definition to the LLVM IR output we're producing.
17 //!
18 //! Hopefully useful general knowledge about codegen:
19 //!
20 //!   * There's no way to find out the Ty type of a Value.  Doing so
21 //!     would be "trying to get the eggs out of an omelette" (credit:
22 //!     pcwalton).  You can, instead, find out its llvm::Type by calling val_ty,
23 //!     but one llvm::Type corresponds to many `Ty`s; for instance, tup(int, int,
24 //!     int) and rec(x=int, y=int, z=int) will have the same llvm::Type.
25
26 use super::ModuleLlvm;
27 use super::ModuleCodegen;
28 use super::ModuleKind;
29 use super::CachedModuleCodegen;
30
31 use abi;
32 use back::write::{self, OngoingCodegen};
33 use llvm::{self, TypeKind, get_param};
34 use metadata;
35 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
36 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
37 use rustc::middle::lang_items::StartFnLangItem;
38 use rustc::middle::weak_lang_items;
39 use rustc::mir::mono::{Linkage, Visibility, Stats, CodegenUnitNameBuilder};
40 use rustc::middle::cstore::{EncodedMetadata};
41 use rustc::ty::{self, Ty, TyCtxt};
42 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf};
43 use rustc::ty::query::Providers;
44 use rustc::middle::cstore::{self, LinkagePreference};
45 use rustc::middle::exported_symbols;
46 use rustc::util::common::{time, print_time_passes_entry};
47 use rustc::util::profiling::ProfileCategory;
48 use rustc::session::config::{self, DebugInfo, EntryFnType, Lto};
49 use rustc::session::Session;
50 use rustc_incremental;
51 use allocator;
52 use mir::place::PlaceRef;
53 use attributes;
54 use builder::{Builder, MemFlags};
55 use callee;
56 use common::{C_bool, C_bytes_in_context, C_usize};
57 use rustc_mir::monomorphize::item::DefPathBasedNames;
58 use common::{C_struct_in_context, C_array, val_ty};
59 use consts;
60 use context::CodegenCx;
61 use debuginfo;
62 use declare;
63 use meth;
64 use mir;
65 use monomorphize::Instance;
66 use monomorphize::partitioning::{CodegenUnit, CodegenUnitExt};
67 use rustc_codegen_utils::symbol_names_test;
68 use time_graph;
69 use mono_item::{MonoItem, MonoItemExt};
70 use type_::Type;
71 use type_of::LayoutLlvmExt;
72 use rustc::util::nodemap::FxHashMap;
73 use CrateInfo;
74 use rustc_data_structures::small_c_str::SmallCStr;
75 use rustc_data_structures::sync::Lrc;
76
77 use std::any::Any;
78 use std::cmp;
79 use std::ffi::CString;
80 use std::ops::{Deref, DerefMut};
81 use std::sync::mpsc;
82 use std::time::{Instant, Duration};
83 use syntax_pos::Span;
84 use syntax_pos::symbol::InternedString;
85 use syntax::attr;
86 use rustc::hir::{self, CodegenFnAttrs};
87
88 use value::Value;
89
90 use mir::operand::OperandValue;
91
92 use rustc_codegen_utils::check_for_rustc_errors_attr;
93
94 pub struct StatRecorder<'a, 'll: 'a, 'tcx: 'll> {
95     cx: &'a CodegenCx<'ll, 'tcx>,
96     name: Option<String>,
97     istart: usize,
98 }
99
100 impl StatRecorder<'a, 'll, 'tcx> {
101     pub fn new(cx: &'a CodegenCx<'ll, 'tcx>, name: String) -> Self {
102         let istart = cx.stats.borrow().n_llvm_insns;
103         StatRecorder {
104             cx,
105             name: Some(name),
106             istart,
107         }
108     }
109 }
110
111 impl Drop for StatRecorder<'a, 'll, 'tcx> {
112     fn drop(&mut self) {
113         if self.cx.sess().codegen_stats() {
114             let mut stats = self.cx.stats.borrow_mut();
115             let iend = stats.n_llvm_insns;
116             stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
117             stats.n_fns += 1;
118             // Reset LLVM insn count to avoid compound costs.
119             stats.n_llvm_insns = self.istart;
120         }
121     }
122 }
123
124 pub fn bin_op_to_icmp_predicate(op: hir::BinOpKind,
125                                 signed: bool)
126                                 -> llvm::IntPredicate {
127     match op {
128         hir::BinOpKind::Eq => llvm::IntEQ,
129         hir::BinOpKind::Ne => llvm::IntNE,
130         hir::BinOpKind::Lt => if signed { llvm::IntSLT } else { llvm::IntULT },
131         hir::BinOpKind::Le => if signed { llvm::IntSLE } else { llvm::IntULE },
132         hir::BinOpKind::Gt => if signed { llvm::IntSGT } else { llvm::IntUGT },
133         hir::BinOpKind::Ge => if signed { llvm::IntSGE } else { llvm::IntUGE },
134         op => {
135             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
136                   found {:?}",
137                  op)
138         }
139     }
140 }
141
142 pub fn bin_op_to_fcmp_predicate(op: hir::BinOpKind) -> llvm::RealPredicate {
143     match op {
144         hir::BinOpKind::Eq => llvm::RealOEQ,
145         hir::BinOpKind::Ne => llvm::RealUNE,
146         hir::BinOpKind::Lt => llvm::RealOLT,
147         hir::BinOpKind::Le => llvm::RealOLE,
148         hir::BinOpKind::Gt => llvm::RealOGT,
149         hir::BinOpKind::Ge => llvm::RealOGE,
150         op => {
151             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
152                   found {:?}",
153                  op);
154         }
155     }
156 }
157
158 pub fn compare_simd_types(
159     bx: &Builder<'a, 'll, 'tcx>,
160     lhs: &'ll Value,
161     rhs: &'ll Value,
162     t: Ty<'tcx>,
163     ret_ty: &'ll Type,
164     op: hir::BinOpKind
165 ) -> &'ll Value {
166     let signed = match t.sty {
167         ty::Float(_) => {
168             let cmp = bin_op_to_fcmp_predicate(op);
169             return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
170         },
171         ty::Uint(_) => false,
172         ty::Int(_) => true,
173         _ => bug!("compare_simd_types: invalid SIMD type"),
174     };
175
176     let cmp = bin_op_to_icmp_predicate(op, signed);
177     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
178     // to get the correctly sized type. This will compile to a single instruction
179     // once the IR is converted to assembly if the SIMD instruction is supported
180     // by the target architecture.
181     bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
182 }
183
184 /// Retrieve the information we are losing (making dynamic) in an unsizing
185 /// adjustment.
186 ///
187 /// The `old_info` argument is a bit funny. It is intended for use
188 /// in an upcast, where the new vtable for an object will be derived
189 /// from the old one.
190 pub fn unsized_info(
191     cx: &CodegenCx<'ll, 'tcx>,
192     source: Ty<'tcx>,
193     target: Ty<'tcx>,
194     old_info: Option<&'ll Value>,
195 ) -> &'ll Value {
196     let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
197     match (&source.sty, &target.sty) {
198         (&ty::Array(_, len), &ty::Slice(_)) => {
199             C_usize(cx, len.unwrap_usize(cx.tcx))
200         }
201         (&ty::Dynamic(..), &ty::Dynamic(..)) => {
202             // For now, upcasts are limited to changes in marker
203             // traits, and hence never actually require an actual
204             // change to the vtable.
205             old_info.expect("unsized_info: missing old info for trait upcast")
206         }
207         (_, &ty::Dynamic(ref data, ..)) => {
208             let vtable_ptr = cx.layout_of(cx.tcx.mk_mut_ptr(target))
209                 .field(cx, abi::FAT_PTR_EXTRA);
210             consts::ptrcast(meth::get_vtable(cx, source, data.principal()),
211                             vtable_ptr.llvm_type(cx))
212         }
213         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
214                   source,
215                   target),
216     }
217 }
218
219 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
220 pub fn unsize_thin_ptr(
221     bx: &Builder<'a, 'll, 'tcx>,
222     src: &'ll Value,
223     src_ty: Ty<'tcx>,
224     dst_ty: Ty<'tcx>
225 ) -> (&'ll Value, &'ll Value) {
226     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
227     match (&src_ty.sty, &dst_ty.sty) {
228         (&ty::Ref(_, a, _),
229          &ty::Ref(_, b, _)) |
230         (&ty::Ref(_, a, _),
231          &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
232         (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
233          &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
234             assert!(bx.cx.type_is_sized(a));
235             let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
236             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
237         }
238         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
239             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
240             assert!(bx.cx.type_is_sized(a));
241             let ptr_ty = bx.cx.layout_of(b).llvm_type(bx.cx).ptr_to();
242             (bx.pointercast(src, ptr_ty), unsized_info(bx.cx, a, b, None))
243         }
244         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
245             assert_eq!(def_a, def_b);
246
247             let src_layout = bx.cx.layout_of(src_ty);
248             let dst_layout = bx.cx.layout_of(dst_ty);
249             let mut result = None;
250             for i in 0..src_layout.fields.count() {
251                 let src_f = src_layout.field(bx.cx, i);
252                 assert_eq!(src_layout.fields.offset(i).bytes(), 0);
253                 assert_eq!(dst_layout.fields.offset(i).bytes(), 0);
254                 if src_f.is_zst() {
255                     continue;
256                 }
257                 assert_eq!(src_layout.size, src_f.size);
258
259                 let dst_f = dst_layout.field(bx.cx, i);
260                 assert_ne!(src_f.ty, dst_f.ty);
261                 assert_eq!(result, None);
262                 result = Some(unsize_thin_ptr(bx, src, src_f.ty, dst_f.ty));
263             }
264             let (lldata, llextra) = result.unwrap();
265             // HACK(eddyb) have to bitcast pointers until LLVM removes pointee types.
266             (bx.bitcast(lldata, dst_layout.scalar_pair_element_llvm_type(bx.cx, 0, true)),
267              bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1, true)))
268         }
269         _ => bug!("unsize_thin_ptr: called on bad types"),
270     }
271 }
272
273 /// Coerce `src`, which is a reference to a value of type `src_ty`,
274 /// to a value of type `dst_ty` and store the result in `dst`
275 pub fn coerce_unsized_into(
276     bx: &Builder<'a, 'll, 'tcx>,
277     src: PlaceRef<'ll, 'tcx>,
278     dst: PlaceRef<'ll, 'tcx>
279 ) {
280     let src_ty = src.layout.ty;
281     let dst_ty = dst.layout.ty;
282     let coerce_ptr = || {
283         let (base, info) = match src.load(bx).val {
284             OperandValue::Pair(base, info) => {
285                 // fat-ptr to fat-ptr unsize preserves the vtable
286                 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
287                 // So we need to pointercast the base to ensure
288                 // the types match up.
289                 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
290                 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
291             }
292             OperandValue::Immediate(base) => {
293                 unsize_thin_ptr(bx, base, src_ty, dst_ty)
294             }
295             OperandValue::Ref(..) => bug!()
296         };
297         OperandValue::Pair(base, info).store(bx, dst);
298     };
299     match (&src_ty.sty, &dst_ty.sty) {
300         (&ty::Ref(..), &ty::Ref(..)) |
301         (&ty::Ref(..), &ty::RawPtr(..)) |
302         (&ty::RawPtr(..), &ty::RawPtr(..)) => {
303             coerce_ptr()
304         }
305         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
306             coerce_ptr()
307         }
308
309         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => {
310             assert_eq!(def_a, def_b);
311
312             for i in 0..def_a.variants[0].fields.len() {
313                 let src_f = src.project_field(bx, i);
314                 let dst_f = dst.project_field(bx, i);
315
316                 if dst_f.layout.is_zst() {
317                     continue;
318                 }
319
320                 if src_f.layout.ty == dst_f.layout.ty {
321                     memcpy_ty(bx, dst_f.llval, dst_f.align, src_f.llval, src_f.align,
322                               src_f.layout, MemFlags::empty());
323                 } else {
324                     coerce_unsized_into(bx, src_f, dst_f);
325                 }
326             }
327         }
328         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
329                   src_ty,
330                   dst_ty),
331     }
332 }
333
334 pub fn cast_shift_expr_rhs(
335     cx: &Builder<'_, 'll, '_>, op: hir::BinOpKind, lhs: &'ll Value, rhs: &'ll Value
336 ) -> &'ll Value {
337     cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
338 }
339
340 fn cast_shift_rhs<'ll, F, G>(op: hir::BinOpKind,
341                              lhs: &'ll Value,
342                              rhs: &'ll Value,
343                              trunc: F,
344                              zext: G)
345                              -> &'ll Value
346     where F: FnOnce(&'ll Value, &'ll Type) -> &'ll Value,
347           G: FnOnce(&'ll Value, &'ll Type) -> &'ll Value
348 {
349     // Shifts may have any size int on the rhs
350     if op.is_shift() {
351         let mut rhs_llty = val_ty(rhs);
352         let mut lhs_llty = val_ty(lhs);
353         if rhs_llty.kind() == TypeKind::Vector {
354             rhs_llty = rhs_llty.element_type()
355         }
356         if lhs_llty.kind() == TypeKind::Vector {
357             lhs_llty = lhs_llty.element_type()
358         }
359         let rhs_sz = rhs_llty.int_width();
360         let lhs_sz = lhs_llty.int_width();
361         if lhs_sz < rhs_sz {
362             trunc(rhs, lhs_llty)
363         } else if lhs_sz > rhs_sz {
364             // FIXME (#1877: If in the future shifting by negative
365             // values is no longer undefined then this is wrong.
366             zext(rhs, lhs_llty)
367         } else {
368             rhs
369         }
370     } else {
371         rhs
372     }
373 }
374
375 /// Returns whether this session's target will use SEH-based unwinding.
376 ///
377 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
378 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
379 /// 64-bit MinGW) instead of "full SEH".
380 pub fn wants_msvc_seh(sess: &Session) -> bool {
381     sess.target.target.options.is_like_msvc
382 }
383
384 pub fn call_assume(bx: &Builder<'_, 'll, '_>, val: &'ll Value) {
385     let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
386     bx.call(assume_intrinsic, &[val], None);
387 }
388
389 pub fn from_immediate(bx: &Builder<'_, 'll, '_>, val: &'ll Value) -> &'ll Value {
390     if val_ty(val) == Type::i1(bx.cx) {
391         bx.zext(val, Type::i8(bx.cx))
392     } else {
393         val
394     }
395 }
396
397 pub fn to_immediate(
398     bx: &Builder<'_, 'll, '_>,
399     val: &'ll Value,
400     layout: layout::TyLayout,
401 ) -> &'ll Value {
402     if let layout::Abi::Scalar(ref scalar) = layout.abi {
403         return to_immediate_scalar(bx, val, scalar);
404     }
405     val
406 }
407
408 pub fn to_immediate_scalar(
409     bx: &Builder<'_, 'll, '_>,
410     val: &'ll Value,
411     scalar: &layout::Scalar,
412 ) -> &'ll Value {
413     if scalar.is_bool() {
414         return bx.trunc(val, Type::i1(bx.cx));
415     }
416     val
417 }
418
419 pub fn call_memcpy(
420     bx: &Builder<'_, 'll, '_>,
421     dst: &'ll Value,
422     dst_align: Align,
423     src: &'ll Value,
424     src_align: Align,
425     n_bytes: &'ll Value,
426     flags: MemFlags,
427 ) {
428     if flags.contains(MemFlags::NONTEMPORAL) {
429         // HACK(nox): This is inefficient but there is no nontemporal memcpy.
430         let val = bx.load(src, src_align);
431         let ptr = bx.pointercast(dst, val_ty(val).ptr_to());
432         bx.store_with_flags(val, ptr, dst_align, flags);
433         return;
434     }
435     let cx = bx.cx;
436     let src_ptr = bx.pointercast(src, Type::i8p(cx));
437     let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
438     let size = bx.intcast(n_bytes, cx.isize_ty, false);
439     let volatile = flags.contains(MemFlags::VOLATILE);
440     bx.memcpy(dst_ptr, dst_align.abi(), src_ptr, src_align.abi(), size, volatile);
441 }
442
443 pub fn memcpy_ty(
444     bx: &Builder<'_, 'll, 'tcx>,
445     dst: &'ll Value,
446     dst_align: Align,
447     src: &'ll Value,
448     src_align: Align,
449     layout: TyLayout<'tcx>,
450     flags: MemFlags,
451 ) {
452     let size = layout.size.bytes();
453     if size == 0 {
454         return;
455     }
456
457     call_memcpy(bx, dst, dst_align, src, src_align, C_usize(bx.cx, size), flags);
458 }
459
460 pub fn call_memset(
461     bx: &Builder<'_, 'll, '_>,
462     ptr: &'ll Value,
463     fill_byte: &'ll Value,
464     size: &'ll Value,
465     align: &'ll Value,
466     volatile: bool,
467 ) -> &'ll Value {
468     let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
469     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
470     let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
471     let volatile = C_bool(bx.cx, volatile);
472     bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
473 }
474
475 pub fn codegen_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
476     let _s = if cx.sess().codegen_stats() {
477         let mut instance_name = String::new();
478         DefPathBasedNames::new(cx.tcx, true, true)
479             .push_def_path(instance.def_id(), &mut instance_name);
480         Some(StatRecorder::new(cx, instance_name))
481     } else {
482         None
483     };
484
485     // this is an info! to allow collecting monomorphization statistics
486     // and to allow finding the last function before LLVM aborts from
487     // release builds.
488     info!("codegen_instance({})", instance);
489
490     let sig = instance.fn_sig(cx.tcx);
491     let sig = cx.tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
492
493     let lldecl = cx.instances.borrow().get(&instance).cloned().unwrap_or_else(||
494         bug!("Instance `{:?}` not already declared", instance));
495
496     cx.stats.borrow_mut().n_closures += 1;
497
498     let mir = cx.tcx.instance_mir(instance.def);
499     mir::codegen_mir(cx, lldecl, &mir, instance, sig);
500 }
501
502 pub fn set_link_section(llval: &Value, attrs: &CodegenFnAttrs) {
503     let sect = match attrs.link_section {
504         Some(name) => name,
505         None => return,
506     };
507     unsafe {
508         let buf = SmallCStr::new(&sect.as_str());
509         llvm::LLVMSetSection(llval, buf.as_ptr());
510     }
511 }
512
513 /// Create the `main` function which will initialize the rust runtime and call
514 /// users main function.
515 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
516     let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
517         Some((id, span, _)) => {
518             (cx.tcx.hir.local_def_id(id), span)
519         }
520         None => return,
521     };
522
523     let instance = Instance::mono(cx.tcx, main_def_id);
524
525     if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
526         // We want to create the wrapper in the same codegen unit as Rust's main
527         // function.
528         return;
529     }
530
531     let main_llfn = callee::get_fn(cx, instance);
532
533     let et = cx.sess().entry_fn.get().map(|e| e.2);
534     match et {
535         Some(EntryFnType::Main) => create_entry_fn(cx, span, main_llfn, main_def_id, true),
536         Some(EntryFnType::Start) => create_entry_fn(cx, span, main_llfn, main_def_id, false),
537         None => {}    // Do nothing.
538     }
539
540     fn create_entry_fn(
541         cx: &CodegenCx<'ll, '_>,
542         sp: Span,
543         rust_main: &'ll Value,
544         rust_main_def_id: DefId,
545         use_start_lang_item: bool,
546     ) {
547         let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], Type::c_int(cx));
548
549         let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
550         // Given that `main()` has no arguments,
551         // then its return type cannot have
552         // late-bound regions, since late-bound
553         // regions must appear in the argument
554         // listing.
555         let main_ret_ty = cx.tcx.erase_regions(
556             &main_ret_ty.no_bound_vars().unwrap(),
557         );
558
559         if declare::get_defined_value(cx, "main").is_some() {
560             // FIXME: We should be smart and show a better diagnostic here.
561             cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
562                      .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
563                      .emit();
564             cx.sess().abort_if_errors();
565             bug!();
566         }
567         let llfn = declare::declare_cfn(cx, "main", llfty);
568
569         // `main` should respect same config for frame pointer elimination as rest of code
570         attributes::set_frame_pointer_elimination(cx, llfn);
571         attributes::apply_target_cpu_attr(cx, llfn);
572
573         let bx = Builder::new_block(cx, llfn, "top");
574
575         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
576
577         // Params from native main() used as args for rust start function
578         let param_argc = get_param(llfn, 0);
579         let param_argv = get_param(llfn, 1);
580         let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
581         let arg_argv = param_argv;
582
583         let (start_fn, args) = if use_start_lang_item {
584             let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
585             let start_fn = callee::resolve_and_get_fn(
586                 cx,
587                 start_def_id,
588                 cx.tcx.intern_substs(&[main_ret_ty.into()]),
589             );
590             (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
591                             arg_argc, arg_argv])
592         } else {
593             debug!("using user-defined start fn");
594             (rust_main, vec![arg_argc, arg_argv])
595         };
596
597         let result = bx.call(start_fn, &args, None);
598         bx.ret(bx.intcast(result, Type::c_int(cx), true));
599     }
600 }
601
602 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
603                             llvm_module: &ModuleLlvm)
604                             -> EncodedMetadata {
605     use std::io::Write;
606     use flate2::Compression;
607     use flate2::write::DeflateEncoder;
608
609     let (metadata_llcx, metadata_llmod) = (&*llvm_module.llcx, llvm_module.llmod());
610
611     #[derive(PartialEq, Eq, PartialOrd, Ord)]
612     enum MetadataKind {
613         None,
614         Uncompressed,
615         Compressed
616     }
617
618     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
619         match *ty {
620             config::CrateType::Executable |
621             config::CrateType::Staticlib |
622             config::CrateType::Cdylib => MetadataKind::None,
623
624             config::CrateType::Rlib => MetadataKind::Uncompressed,
625
626             config::CrateType::Dylib |
627             config::CrateType::ProcMacro => MetadataKind::Compressed,
628         }
629     }).max().unwrap_or(MetadataKind::None);
630
631     if kind == MetadataKind::None {
632         return EncodedMetadata::new();
633     }
634
635     let metadata = tcx.encode_metadata();
636     if kind == MetadataKind::Uncompressed {
637         return metadata;
638     }
639
640     assert!(kind == MetadataKind::Compressed);
641     let mut compressed = tcx.metadata_encoding_version();
642     DeflateEncoder::new(&mut compressed, Compression::fast())
643         .write_all(&metadata.raw_data).unwrap();
644
645     let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
646     let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
647     let name = exported_symbols::metadata_symbol_name(tcx);
648     let buf = CString::new(name).unwrap();
649     let llglobal = unsafe {
650         llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst), buf.as_ptr())
651     };
652     unsafe {
653         llvm::LLVMSetInitializer(llglobal, llconst);
654         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
655         let name = SmallCStr::new(section_name);
656         llvm::LLVMSetSection(llglobal, name.as_ptr());
657
658         // Also generate a .section directive to force no
659         // flags, at least for ELF outputs, so that the
660         // metadata doesn't get loaded into memory.
661         let directive = format!(".section {}", section_name);
662         let directive = CString::new(directive).unwrap();
663         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
664     }
665     return metadata;
666 }
667
668 pub struct ValueIter<'ll> {
669     cur: Option<&'ll Value>,
670     step: unsafe extern "C" fn(&'ll Value) -> Option<&'ll Value>,
671 }
672
673 impl Iterator for ValueIter<'ll> {
674     type Item = &'ll Value;
675
676     fn next(&mut self) -> Option<&'ll Value> {
677         let old = self.cur;
678         if let Some(old) = old {
679             self.cur = unsafe { (self.step)(old) };
680         }
681         old
682     }
683 }
684
685 pub fn iter_globals(llmod: &'ll llvm::Module) -> ValueIter<'ll> {
686     unsafe {
687         ValueIter {
688             cur: llvm::LLVMGetFirstGlobal(llmod),
689             step: llvm::LLVMGetNextGlobal,
690         }
691     }
692 }
693
694 fn determine_cgu_reuse<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
695                                  cgu: &CodegenUnit<'tcx>)
696                                  -> CguReuse {
697     if !tcx.dep_graph.is_fully_enabled() {
698         return CguReuse::No
699     }
700
701     let work_product_id = &cgu.work_product_id();
702     if tcx.dep_graph.previous_work_product(work_product_id).is_none() {
703         // We don't have anything cached for this CGU. This can happen
704         // if the CGU did not exist in the previous session.
705         return CguReuse::No
706     }
707
708     // Try to mark the CGU as green. If it we can do so, it means that nothing
709     // affecting the LLVM module has changed and we can re-use a cached version.
710     // If we compile with any kind of LTO, this means we can re-use the bitcode
711     // of the Pre-LTO stage (possibly also the Post-LTO version but we'll only
712     // know that later). If we are not doing LTO, there is only one optimized
713     // version of each module, so we re-use that.
714     let dep_node = cgu.codegen_dep_node(tcx);
715     assert!(!tcx.dep_graph.dep_node_exists(&dep_node),
716         "CompileCodegenUnit dep-node for CGU `{}` already exists before marking.",
717         cgu.name());
718
719     if tcx.dep_graph.try_mark_green(tcx, &dep_node).is_some() {
720         // We can re-use either the pre- or the post-thinlto state
721         if tcx.sess.lto() != Lto::No {
722             CguReuse::PreLto
723         } else {
724             CguReuse::PostLto
725         }
726     } else {
727         CguReuse::No
728     }
729 }
730
731 pub fn codegen_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
732                                rx: mpsc::Receiver<Box<dyn Any + Send>>)
733                                -> OngoingCodegen
734 {
735     check_for_rustc_errors_attr(tcx);
736
737     let cgu_name_builder = &mut CodegenUnitNameBuilder::new(tcx);
738
739     // Codegen the metadata.
740     tcx.sess.profiler(|p| p.start_activity(ProfileCategory::Codegen));
741
742     let metadata_cgu_name = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
743                                                             &["crate"],
744                                                             Some("metadata")).as_str()
745                                                                              .to_string();
746     let metadata_llvm_module = ModuleLlvm::new(tcx.sess, &metadata_cgu_name);
747     let metadata = time(tcx.sess, "write metadata", || {
748         write_metadata(tcx, &metadata_llvm_module)
749     });
750     tcx.sess.profiler(|p| p.end_activity(ProfileCategory::Codegen));
751
752     let metadata_module = ModuleCodegen {
753         name: metadata_cgu_name,
754         module_llvm: metadata_llvm_module,
755         kind: ModuleKind::Metadata,
756     };
757
758     let time_graph = if tcx.sess.opts.debugging_opts.codegen_time_graph {
759         Some(time_graph::TimeGraph::new())
760     } else {
761         None
762     };
763
764     // Skip crate items and just output metadata in -Z no-codegen mode.
765     if tcx.sess.opts.debugging_opts.no_codegen ||
766        !tcx.sess.opts.output_types.should_codegen() {
767         let ongoing_codegen = write::start_async_codegen(
768             tcx,
769             time_graph,
770             metadata,
771             rx,
772             1);
773
774         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
775         ongoing_codegen.codegen_finished(tcx);
776
777         assert_and_save_dep_graph(tcx);
778
779         ongoing_codegen.check_for_errors(tcx.sess);
780
781         return ongoing_codegen;
782     }
783
784     // Run the monomorphization collector and partition the collected items into
785     // codegen units.
786     let codegen_units = tcx.collect_and_partition_mono_items(LOCAL_CRATE).1;
787     let codegen_units = (*codegen_units).clone();
788
789     // Force all codegen_unit queries so they are already either red or green
790     // when compile_codegen_unit accesses them. We are not able to re-execute
791     // the codegen_unit query from just the DepNode, so an unknown color would
792     // lead to having to re-execute compile_codegen_unit, possibly
793     // unnecessarily.
794     if tcx.dep_graph.is_fully_enabled() {
795         for cgu in &codegen_units {
796             tcx.codegen_unit(cgu.name().clone());
797         }
798     }
799
800     let ongoing_codegen = write::start_async_codegen(
801         tcx,
802         time_graph.clone(),
803         metadata,
804         rx,
805         codegen_units.len());
806     let ongoing_codegen = AbortCodegenOnDrop(Some(ongoing_codegen));
807
808     // Codegen an allocator shim, if necessary.
809     //
810     // If the crate doesn't have an `allocator_kind` set then there's definitely
811     // no shim to generate. Otherwise we also check our dependency graph for all
812     // our output crate types. If anything there looks like its a `Dynamic`
813     // linkage, then it's already got an allocator shim and we'll be using that
814     // one instead. If nothing exists then it's our job to generate the
815     // allocator!
816     let any_dynamic_crate = tcx.sess.dependency_formats.borrow()
817         .iter()
818         .any(|(_, list)| {
819             use rustc::middle::dependency_format::Linkage;
820             list.iter().any(|&linkage| linkage == Linkage::Dynamic)
821         });
822     let allocator_module = if any_dynamic_crate {
823         None
824     } else if let Some(kind) = *tcx.sess.allocator_kind.get() {
825         let llmod_id = cgu_name_builder.build_cgu_name(LOCAL_CRATE,
826                                                        &["crate"],
827                                                        Some("allocator")).as_str()
828                                                                          .to_string();
829         let modules = ModuleLlvm::new(tcx.sess, &llmod_id);
830         time(tcx.sess, "write allocator module", || {
831             unsafe {
832                 allocator::codegen(tcx, &modules, kind)
833             }
834         });
835
836         Some(ModuleCodegen {
837             name: llmod_id,
838             module_llvm: modules,
839             kind: ModuleKind::Allocator,
840         })
841     } else {
842         None
843     };
844
845     if let Some(allocator_module) = allocator_module {
846         ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, allocator_module);
847     }
848
849     ongoing_codegen.submit_pre_codegened_module_to_llvm(tcx, metadata_module);
850
851     // We sort the codegen units by size. This way we can schedule work for LLVM
852     // a bit more efficiently.
853     let codegen_units = {
854         let mut codegen_units = codegen_units;
855         codegen_units.sort_by_cached_key(|cgu| cmp::Reverse(cgu.size_estimate()));
856         codegen_units
857     };
858
859     let mut total_codegen_time = Duration::new(0, 0);
860     let mut all_stats = Stats::default();
861
862     for cgu in codegen_units.into_iter() {
863         ongoing_codegen.wait_for_signal_to_codegen_item();
864         ongoing_codegen.check_for_errors(tcx.sess);
865
866         let cgu_reuse = determine_cgu_reuse(tcx, &cgu);
867         tcx.sess.cgu_reuse_tracker.set_actual_reuse(&cgu.name().as_str(), cgu_reuse);
868
869         match cgu_reuse {
870             CguReuse::No => {
871                 let _timing_guard = time_graph.as_ref().map(|time_graph| {
872                     time_graph.start(write::CODEGEN_WORKER_TIMELINE,
873                                      write::CODEGEN_WORK_PACKAGE_KIND,
874                                      &format!("codegen {}", cgu.name()))
875                 });
876                 let start_time = Instant::now();
877                 let stats = compile_codegen_unit(tcx, *cgu.name());
878                 all_stats.extend(stats);
879                 total_codegen_time += start_time.elapsed();
880                 false
881             }
882             CguReuse::PreLto => {
883                 write::submit_pre_lto_module_to_llvm(tcx, CachedModuleCodegen {
884                     name: cgu.name().to_string(),
885                     source: cgu.work_product(tcx),
886                 });
887                 true
888             }
889             CguReuse::PostLto => {
890                 write::submit_post_lto_module_to_llvm(tcx, CachedModuleCodegen {
891                     name: cgu.name().to_string(),
892                     source: cgu.work_product(tcx),
893                 });
894                 true
895             }
896         };
897     }
898
899     ongoing_codegen.codegen_finished(tcx);
900
901     // Since the main thread is sometimes blocked during codegen, we keep track
902     // -Ztime-passes output manually.
903     print_time_passes_entry(tcx.sess.time_passes(),
904                             "codegen to LLVM IR",
905                             total_codegen_time);
906
907     rustc_incremental::assert_module_sources::assert_module_sources(tcx);
908
909     symbol_names_test::report_symbol_names(tcx);
910
911     if tcx.sess.codegen_stats() {
912         println!("--- codegen stats ---");
913         println!("n_glues_created: {}", all_stats.n_glues_created);
914         println!("n_null_glues: {}", all_stats.n_null_glues);
915         println!("n_real_glues: {}", all_stats.n_real_glues);
916
917         println!("n_fns: {}", all_stats.n_fns);
918         println!("n_inlines: {}", all_stats.n_inlines);
919         println!("n_closures: {}", all_stats.n_closures);
920         println!("fn stats:");
921         all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
922         for &(ref name, insns) in all_stats.fn_stats.iter() {
923             println!("{} insns, {}", insns, *name);
924         }
925     }
926
927     if tcx.sess.count_llvm_insns() {
928         for (k, v) in all_stats.llvm_insns.iter() {
929             println!("{:7} {}", *v, *k);
930         }
931     }
932
933     ongoing_codegen.check_for_errors(tcx.sess);
934
935     assert_and_save_dep_graph(tcx);
936     ongoing_codegen.into_inner()
937 }
938
939 /// A curious wrapper structure whose only purpose is to call `codegen_aborted`
940 /// when it's dropped abnormally.
941 ///
942 /// In the process of working on rust-lang/rust#55238 a mysterious segfault was
943 /// stumbled upon. The segfault was never reproduced locally, but it was
944 /// suspected to be releated to the fact that codegen worker threads were
945 /// sticking around by the time the main thread was exiting, causing issues.
946 ///
947 /// This structure is an attempt to fix that issue where the `codegen_aborted`
948 /// message will block until all workers have finished. This should ensure that
949 /// even if the main codegen thread panics we'll wait for pending work to
950 /// complete before returning from the main thread, hopefully avoiding
951 /// segfaults.
952 ///
953 /// If you see this comment in the code, then it means that this workaround
954 /// worked! We may yet one day track down the mysterious cause of that
955 /// segfault...
956 struct AbortCodegenOnDrop(Option<OngoingCodegen>);
957
958 impl AbortCodegenOnDrop {
959     fn into_inner(mut self) -> OngoingCodegen {
960         self.0.take().unwrap()
961     }
962 }
963
964 impl Deref for AbortCodegenOnDrop {
965     type Target = OngoingCodegen;
966
967     fn deref(&self) -> &OngoingCodegen {
968         self.0.as_ref().unwrap()
969     }
970 }
971
972 impl DerefMut for AbortCodegenOnDrop {
973     fn deref_mut(&mut self) -> &mut OngoingCodegen {
974         self.0.as_mut().unwrap()
975     }
976 }
977
978 impl Drop for AbortCodegenOnDrop {
979     fn drop(&mut self) {
980         if let Some(codegen) = self.0.take() {
981             codegen.codegen_aborted();
982         }
983     }
984 }
985
986 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
987     time(tcx.sess,
988          "assert dep graph",
989          || rustc_incremental::assert_dep_graph(tcx));
990
991     time(tcx.sess,
992          "serialize dep graph",
993          || rustc_incremental::save_dep_graph(tcx));
994 }
995
996 impl CrateInfo {
997     pub fn new(tcx: TyCtxt) -> CrateInfo {
998         let mut info = CrateInfo {
999             panic_runtime: None,
1000             compiler_builtins: None,
1001             profiler_runtime: None,
1002             sanitizer_runtime: None,
1003             is_no_builtins: Default::default(),
1004             native_libraries: Default::default(),
1005             used_libraries: tcx.native_libraries(LOCAL_CRATE),
1006             link_args: tcx.link_args(LOCAL_CRATE),
1007             crate_name: Default::default(),
1008             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1009             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1010             used_crate_source: Default::default(),
1011             wasm_imports: Default::default(),
1012             lang_item_to_crate: Default::default(),
1013             missing_lang_items: Default::default(),
1014         };
1015         let lang_items = tcx.lang_items();
1016
1017         let load_wasm_items = tcx.sess.crate_types.borrow()
1018             .iter()
1019             .any(|c| *c != config::CrateType::Rlib) &&
1020             tcx.sess.opts.target_triple.triple() == "wasm32-unknown-unknown";
1021
1022         if load_wasm_items {
1023             info.load_wasm_imports(tcx, LOCAL_CRATE);
1024         }
1025
1026         let crates = tcx.crates();
1027
1028         let n_crates = crates.len();
1029         info.native_libraries.reserve(n_crates);
1030         info.crate_name.reserve(n_crates);
1031         info.used_crate_source.reserve(n_crates);
1032         info.missing_lang_items.reserve(n_crates);
1033
1034         for &cnum in crates.iter() {
1035             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1036             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1037             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1038             if tcx.is_panic_runtime(cnum) {
1039                 info.panic_runtime = Some(cnum);
1040             }
1041             if tcx.is_compiler_builtins(cnum) {
1042                 info.compiler_builtins = Some(cnum);
1043             }
1044             if tcx.is_profiler_runtime(cnum) {
1045                 info.profiler_runtime = Some(cnum);
1046             }
1047             if tcx.is_sanitizer_runtime(cnum) {
1048                 info.sanitizer_runtime = Some(cnum);
1049             }
1050             if tcx.is_no_builtins(cnum) {
1051                 info.is_no_builtins.insert(cnum);
1052             }
1053             if load_wasm_items {
1054                 info.load_wasm_imports(tcx, cnum);
1055             }
1056             let missing = tcx.missing_lang_items(cnum);
1057             for &item in missing.iter() {
1058                 if let Ok(id) = lang_items.require(item) {
1059                     info.lang_item_to_crate.insert(item, id.krate);
1060                 }
1061             }
1062
1063             // No need to look for lang items that are whitelisted and don't
1064             // actually need to exist.
1065             let missing = missing.iter()
1066                 .cloned()
1067                 .filter(|&l| !weak_lang_items::whitelisted(tcx, l))
1068                 .collect();
1069             info.missing_lang_items.insert(cnum, missing);
1070         }
1071
1072         return info
1073     }
1074
1075     fn load_wasm_imports(&mut self, tcx: TyCtxt, cnum: CrateNum) {
1076         self.wasm_imports.extend(tcx.wasm_import_module_map(cnum).iter().map(|(&id, module)| {
1077             let instance = Instance::mono(tcx, id);
1078             let import_name = tcx.symbol_name(instance);
1079
1080             (import_name.to_string(), module.clone())
1081         }));
1082     }
1083 }
1084
1085 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1086                                   cgu_name: InternedString)
1087                                   -> Stats {
1088     let start_time = Instant::now();
1089
1090     let dep_node = tcx.codegen_unit(cgu_name).codegen_dep_node(tcx);
1091     let ((stats, module), _) = tcx.dep_graph.with_task(dep_node,
1092                                                        tcx,
1093                                                        cgu_name,
1094                                                        module_codegen);
1095     let time_to_codegen = start_time.elapsed();
1096
1097     // We assume that the cost to run LLVM on a CGU is proportional to
1098     // the time we needed for codegenning it.
1099     let cost = time_to_codegen.as_secs() * 1_000_000_000 +
1100                time_to_codegen.subsec_nanos() as u64;
1101
1102     write::submit_codegened_module_to_llvm(tcx,
1103                                            module,
1104                                            cost);
1105     return stats;
1106
1107     fn module_codegen<'a, 'tcx>(
1108         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1109         cgu_name: InternedString)
1110         -> (Stats, ModuleCodegen)
1111     {
1112         let cgu = tcx.codegen_unit(cgu_name);
1113
1114         // Instantiate monomorphizations without filling out definitions yet...
1115         let llvm_module = ModuleLlvm::new(tcx.sess, &cgu_name.as_str());
1116         let stats = {
1117             let cx = CodegenCx::new(tcx, cgu, &llvm_module);
1118             let mono_items = cx.codegen_unit
1119                                .items_in_deterministic_order(cx.tcx);
1120             for &(mono_item, (linkage, visibility)) in &mono_items {
1121                 mono_item.predefine(&cx, linkage, visibility);
1122             }
1123
1124             // ... and now that we have everything pre-defined, fill out those definitions.
1125             for &(mono_item, _) in &mono_items {
1126                 mono_item.define(&cx);
1127             }
1128
1129             // If this codegen unit contains the main function, also create the
1130             // wrapper here
1131             maybe_create_entry_wrapper(&cx);
1132
1133             // Run replace-all-uses-with for statics that need it
1134             for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1135                 unsafe {
1136                     let bitcast = llvm::LLVMConstPointerCast(new_g, val_ty(old_g));
1137                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1138                     llvm::LLVMDeleteGlobal(old_g);
1139                 }
1140             }
1141
1142             // Create the llvm.used variable
1143             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1144             if !cx.used_statics.borrow().is_empty() {
1145                 let name = const_cstr!("llvm.used");
1146                 let section = const_cstr!("llvm.metadata");
1147                 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1148
1149                 unsafe {
1150                     let g = llvm::LLVMAddGlobal(cx.llmod,
1151                                                 val_ty(array),
1152                                                 name.as_ptr());
1153                     llvm::LLVMSetInitializer(g, array);
1154                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1155                     llvm::LLVMSetSection(g, section.as_ptr());
1156                 }
1157             }
1158
1159             // Finalize debuginfo
1160             if cx.sess().opts.debuginfo != DebugInfo::None {
1161                 debuginfo::finalize(&cx);
1162             }
1163
1164             cx.stats.into_inner()
1165         };
1166
1167         (stats, ModuleCodegen {
1168             name: cgu_name.to_string(),
1169             module_llvm: llvm_module,
1170             kind: ModuleKind::Regular,
1171         })
1172     }
1173 }
1174
1175 pub fn provide_both(providers: &mut Providers) {
1176     providers.dllimport_foreign_items = |tcx, krate| {
1177         let module_map = tcx.foreign_modules(krate);
1178         let module_map = module_map.iter()
1179             .map(|lib| (lib.def_id, lib))
1180             .collect::<FxHashMap<_, _>>();
1181
1182         let dllimports = tcx.native_libraries(krate)
1183             .iter()
1184             .filter(|lib| {
1185                 if lib.kind != cstore::NativeLibraryKind::NativeUnknown {
1186                     return false
1187                 }
1188                 let cfg = match lib.cfg {
1189                     Some(ref cfg) => cfg,
1190                     None => return true,
1191                 };
1192                 attr::cfg_matches(cfg, &tcx.sess.parse_sess, None)
1193             })
1194             .filter_map(|lib| lib.foreign_module)
1195             .map(|id| &module_map[&id])
1196             .flat_map(|module| module.foreign_items.iter().cloned())
1197             .collect();
1198         Lrc::new(dllimports)
1199     };
1200
1201     providers.is_dllimport_foreign_item = |tcx, def_id| {
1202         tcx.dllimport_foreign_items(def_id.krate).contains(&def_id)
1203     };
1204 }
1205
1206 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1207     match linkage {
1208         Linkage::External => llvm::Linkage::ExternalLinkage,
1209         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1210         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1211         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1212         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1213         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1214         Linkage::Appending => llvm::Linkage::AppendingLinkage,
1215         Linkage::Internal => llvm::Linkage::InternalLinkage,
1216         Linkage::Private => llvm::Linkage::PrivateLinkage,
1217         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1218         Linkage::Common => llvm::Linkage::CommonLinkage,
1219     }
1220 }
1221
1222 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1223     match linkage {
1224         Visibility::Default => llvm::Visibility::Default,
1225         Visibility::Hidden => llvm::Visibility::Hidden,
1226         Visibility::Protected => llvm::Visibility::Protected,
1227     }
1228 }
1229
1230 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1231 //            the HashStable trait. Normally DepGraph::with_task() calls are
1232 //            hidden behind queries, but CGU creation is a special case in two
1233 //            ways: (1) it's not a query and (2) CGU are output nodes, so their
1234 //            Fingerprints are not actually needed. It remains to be clarified
1235 //            how exactly this case will be handled in the red/green system but
1236 //            for now we content ourselves with providing a no-op HashStable
1237 //            implementation for CGUs.
1238 mod temp_stable_hash_impls {
1239     use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1240                                                HashStable};
1241     use ModuleCodegen;
1242
1243     impl<HCX> HashStable<HCX> for ModuleCodegen {
1244         fn hash_stable<W: StableHasherResult>(&self,
1245                                               _: &mut HCX,
1246                                               _: &mut StableHasher<W>) {
1247             // do nothing
1248         }
1249     }
1250 }