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