]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
Refactor away `inferred_obligations` from the trait selector
[rust.git] / src / librustc_trans / 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 //! Translate the completed AST to the LLVM IR.
12 //!
13 //! Some functions here, such as trans_block and trans_expr, return a value --
14 //! the result of the translation to LLVM -- while others, such as trans_fn
15 //! and trans_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 trans:
19 //!
20 //!   * There's no way to find out the Ty type of a ValueRef.  Doing so
21 //!     would be "trying to get the eggs out of an omelette" (credit:
22 //!     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
23 //!     but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
24 //!     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26 use super::ModuleLlvm;
27 use super::ModuleSource;
28 use super::ModuleTranslation;
29 use super::ModuleKind;
30
31 use abi;
32 use back::link;
33 use back::symbol_export;
34 use back::write::{self, OngoingCrateTranslation, create_target_machine};
35 use llvm::{ContextRef, ModuleRef, ValueRef, Vector, get_param};
36 use llvm;
37 use metadata;
38 use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
39 use rustc::middle::lang_items::StartFnLangItem;
40 use rustc::mir::mono::{Linkage, Visibility, Stats};
41 use rustc::middle::cstore::{EncodedMetadata};
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::ty::layout::{self, Align, TyLayout, LayoutOf};
44 use rustc::ty::maps::Providers;
45 use rustc::dep_graph::{DepNode, DepConstructor};
46 use rustc::ty::subst::Kind;
47 use rustc::middle::cstore::{self, LinkMeta, LinkagePreference};
48 use rustc::util::common::{time, print_time_passes_entry};
49 use rustc::session::config::{self, NoDebugInfo};
50 use rustc::session::Session;
51 use rustc_incremental;
52 use allocator;
53 use mir::place::PlaceRef;
54 use attributes;
55 use builder::Builder;
56 use callee;
57 use common::{C_bool, C_bytes_in_context, C_i32, C_usize};
58 use rustc_mir::monomorphize::collector::{self, MonoItemCollectionMode};
59 use common::{self, C_struct_in_context, C_array, val_ty};
60 use consts;
61 use context::{self, CodegenCx};
62 use debuginfo;
63 use declare;
64 use meth;
65 use mir;
66 use monomorphize::Instance;
67 use monomorphize::partitioning::{self, PartitioningStrategy, CodegenUnit, CodegenUnitExt};
68 use rustc_trans_utils::symbol_names_test;
69 use time_graph;
70 use trans_item::{MonoItem, BaseMonoItemExt, MonoItemExt, DefPathBasedNames};
71 use type_::Type;
72 use type_of::LayoutLlvmExt;
73 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet, DefIdSet};
74 use CrateInfo;
75
76 use std::any::Any;
77 use std::ffi::CString;
78 use std::str;
79 use std::sync::Arc;
80 use std::time::{Instant, Duration};
81 use std::{i32, usize};
82 use std::iter;
83 use std::sync::mpsc;
84 use syntax_pos::Span;
85 use syntax_pos::symbol::InternedString;
86 use syntax::attr;
87 use rustc::hir;
88 use syntax::ast;
89
90 use mir::operand::OperandValue;
91
92 pub use rustc_trans_utils::{find_exported_symbols, check_for_rustc_errors_attr};
93 pub use rustc_mir::monomorphize::item::linkage_by_name;
94
95 pub struct StatRecorder<'a, 'tcx: 'a> {
96     cx: &'a CodegenCx<'a, 'tcx>,
97     name: Option<String>,
98     istart: usize,
99 }
100
101 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
102     pub fn new(cx: &'a CodegenCx<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
103         let istart = cx.stats.borrow().n_llvm_insns;
104         StatRecorder {
105             cx,
106             name: Some(name),
107             istart,
108         }
109     }
110 }
111
112 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
113     fn drop(&mut self) {
114         if self.cx.sess().trans_stats() {
115             let mut stats = self.cx.stats.borrow_mut();
116             let iend = stats.n_llvm_insns;
117             stats.fn_stats.push((self.name.take().unwrap(), iend - self.istart));
118             stats.n_fns += 1;
119             // Reset LLVM insn count to avoid compound costs.
120             stats.n_llvm_insns = self.istart;
121         }
122     }
123 }
124
125 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
126                                 signed: bool)
127                                 -> llvm::IntPredicate {
128     match op {
129         hir::BiEq => llvm::IntEQ,
130         hir::BiNe => llvm::IntNE,
131         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
132         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
133         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
134         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
135         op => {
136             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
137                   found {:?}",
138                  op)
139         }
140     }
141 }
142
143 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
144     match op {
145         hir::BiEq => llvm::RealOEQ,
146         hir::BiNe => llvm::RealUNE,
147         hir::BiLt => llvm::RealOLT,
148         hir::BiLe => llvm::RealOLE,
149         hir::BiGt => llvm::RealOGT,
150         hir::BiGe => llvm::RealOGE,
151         op => {
152             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
153                   found {:?}",
154                  op);
155         }
156     }
157 }
158
159 pub fn compare_simd_types<'a, 'tcx>(
160     bx: &Builder<'a, 'tcx>,
161     lhs: ValueRef,
162     rhs: ValueRef,
163     t: Ty<'tcx>,
164     ret_ty: Type,
165     op: hir::BinOp_
166 ) -> ValueRef {
167     let signed = match t.sty {
168         ty::TyFloat(_) => {
169             let cmp = bin_op_to_fcmp_predicate(op);
170             return bx.sext(bx.fcmp(cmp, lhs, rhs), ret_ty);
171         },
172         ty::TyUint(_) => false,
173         ty::TyInt(_) => true,
174         _ => bug!("compare_simd_types: invalid SIMD type"),
175     };
176
177     let cmp = bin_op_to_icmp_predicate(op, signed);
178     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
179     // to get the correctly sized type. This will compile to a single instruction
180     // once the IR is converted to assembly if the SIMD instruction is supported
181     // by the target architecture.
182     bx.sext(bx.icmp(cmp, lhs, rhs), ret_ty)
183 }
184
185 /// Retrieve the information we are losing (making dynamic) in an unsizing
186 /// adjustment.
187 ///
188 /// The `old_info` argument is a bit funny. It is intended for use
189 /// in an upcast, where the new vtable for an object will be derived
190 /// from the old one.
191 pub fn unsized_info<'cx, 'tcx>(cx: &CodegenCx<'cx, 'tcx>,
192                                 source: Ty<'tcx>,
193                                 target: Ty<'tcx>,
194                                 old_info: Option<ValueRef>)
195                                 -> ValueRef {
196     let (source, target) = cx.tcx.struct_lockstep_tails(source, target);
197     match (&source.sty, &target.sty) {
198         (&ty::TyArray(_, len), &ty::TySlice(_)) => {
199             C_usize(cx, len.val.to_const_int().unwrap().to_u64().unwrap())
200         }
201         (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
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::TyDynamic(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<'a, 'tcx>(
221     bx: &Builder<'a, 'tcx>,
222     src: ValueRef,
223     src_ty: Ty<'tcx>,
224     dst_ty: Ty<'tcx>
225 ) -> (ValueRef, ValueRef) {
226     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
227     match (&src_ty.sty, &dst_ty.sty) {
228         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
229          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
230         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
231          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
232         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
233          &ty::TyRawPtr(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::TyAdt(def_a, _), &ty::TyAdt(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::TyAdt(def_a, _), &ty::TyAdt(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)),
267              bx.bitcast(llextra, dst_layout.scalar_pair_element_llvm_type(bx.cx, 1)))
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<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
276                                      src: PlaceRef<'tcx>,
277                                      dst: PlaceRef<'tcx>) {
278     let src_ty = src.layout.ty;
279     let dst_ty = dst.layout.ty;
280     let coerce_ptr = || {
281         let (base, info) = match src.load(bx).val {
282             OperandValue::Pair(base, info) => {
283                 // fat-ptr to fat-ptr unsize preserves the vtable
284                 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
285                 // So we need to pointercast the base to ensure
286                 // the types match up.
287                 let thin_ptr = dst.layout.field(bx.cx, abi::FAT_PTR_ADDR);
288                 (bx.pointercast(base, thin_ptr.llvm_type(bx.cx)), info)
289             }
290             OperandValue::Immediate(base) => {
291                 unsize_thin_ptr(bx, base, src_ty, dst_ty)
292             }
293             OperandValue::Ref(..) => bug!()
294         };
295         OperandValue::Pair(base, info).store(bx, dst);
296     };
297     match (&src_ty.sty, &dst_ty.sty) {
298         (&ty::TyRef(..), &ty::TyRef(..)) |
299         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
300         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
301             coerce_ptr()
302         }
303         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
304             coerce_ptr()
305         }
306
307         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => {
308             assert_eq!(def_a, def_b);
309
310             for i in 0..def_a.variants[0].fields.len() {
311                 let src_f = src.project_field(bx, i);
312                 let dst_f = dst.project_field(bx, i);
313
314                 if dst_f.layout.is_zst() {
315                     continue;
316                 }
317
318                 if src_f.layout.ty == dst_f.layout.ty {
319                     memcpy_ty(bx, dst_f.llval, src_f.llval, src_f.layout,
320                         src_f.align.min(dst_f.align));
321                 } else {
322                     coerce_unsized_into(bx, src_f, dst_f);
323                 }
324             }
325         }
326         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
327                   src_ty,
328                   dst_ty),
329     }
330 }
331
332 pub fn cast_shift_expr_rhs(
333     cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
334 ) -> ValueRef {
335     cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
336 }
337
338 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
339     cast_shift_rhs(op,
340                    lhs,
341                    rhs,
342                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
343                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
344 }
345
346 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
347                         lhs: ValueRef,
348                         rhs: ValueRef,
349                         trunc: F,
350                         zext: G)
351                         -> ValueRef
352     where F: FnOnce(ValueRef, Type) -> ValueRef,
353           G: FnOnce(ValueRef, Type) -> ValueRef
354 {
355     // Shifts may have any size int on the rhs
356     if op.is_shift() {
357         let mut rhs_llty = val_ty(rhs);
358         let mut lhs_llty = val_ty(lhs);
359         if rhs_llty.kind() == Vector {
360             rhs_llty = rhs_llty.element_type()
361         }
362         if lhs_llty.kind() == Vector {
363             lhs_llty = lhs_llty.element_type()
364         }
365         let rhs_sz = rhs_llty.int_width();
366         let lhs_sz = lhs_llty.int_width();
367         if lhs_sz < rhs_sz {
368             trunc(rhs, lhs_llty)
369         } else if lhs_sz > rhs_sz {
370             // FIXME (#1877: If shifting by negative
371             // values becomes not undefined then this is wrong.
372             zext(rhs, lhs_llty)
373         } else {
374             rhs
375         }
376     } else {
377         rhs
378     }
379 }
380
381 /// Returns whether this session's target will use SEH-based unwinding.
382 ///
383 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
384 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
385 /// 64-bit MinGW) instead of "full SEH".
386 pub fn wants_msvc_seh(sess: &Session) -> bool {
387     sess.target.target.options.is_like_msvc
388 }
389
390 pub fn call_assume<'a, 'tcx>(bx: &Builder<'a, 'tcx>, val: ValueRef) {
391     let assume_intrinsic = bx.cx.get_intrinsic("llvm.assume");
392     bx.call(assume_intrinsic, &[val], None);
393 }
394
395 pub fn from_immediate(bx: &Builder, val: ValueRef) -> ValueRef {
396     if val_ty(val) == Type::i1(bx.cx) {
397         bx.zext(val, Type::i8(bx.cx))
398     } else {
399         val
400     }
401 }
402
403 pub fn to_immediate(bx: &Builder, val: ValueRef, layout: layout::TyLayout) -> ValueRef {
404     if let layout::Abi::Scalar(ref scalar) = layout.abi {
405         if scalar.is_bool() {
406             return bx.trunc(val, Type::i1(bx.cx));
407         }
408     }
409     val
410 }
411
412 pub fn call_memcpy(bx: &Builder,
413                    dst: ValueRef,
414                    src: ValueRef,
415                    n_bytes: ValueRef,
416                    align: Align) {
417     let cx = bx.cx;
418     let ptr_width = &cx.sess().target.target.target_pointer_width;
419     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
420     let memcpy = cx.get_intrinsic(&key);
421     let src_ptr = bx.pointercast(src, Type::i8p(cx));
422     let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
423     let size = bx.intcast(n_bytes, cx.isize_ty, false);
424     let align = C_i32(cx, align.abi() as i32);
425     let volatile = C_bool(cx, false);
426     bx.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
427 }
428
429 pub fn memcpy_ty<'a, 'tcx>(
430     bx: &Builder<'a, 'tcx>,
431     dst: ValueRef,
432     src: ValueRef,
433     layout: TyLayout<'tcx>,
434     align: Align,
435 ) {
436     let size = layout.size.bytes();
437     if size == 0 {
438         return;
439     }
440
441     call_memcpy(bx, dst, src, C_usize(bx.cx, size), align);
442 }
443
444 pub fn call_memset<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
445                              ptr: ValueRef,
446                              fill_byte: ValueRef,
447                              size: ValueRef,
448                              align: ValueRef,
449                              volatile: bool) -> ValueRef {
450     let ptr_width = &bx.cx.sess().target.target.target_pointer_width;
451     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
452     let llintrinsicfn = bx.cx.get_intrinsic(&intrinsic_key);
453     let volatile = C_bool(bx.cx, volatile);
454     bx.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
455 }
456
457 pub fn trans_instance<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>, instance: Instance<'tcx>) {
458     let _s = if cx.sess().trans_stats() {
459         let mut instance_name = String::new();
460         DefPathBasedNames::new(cx.tcx, true, true)
461             .push_def_path(instance.def_id(), &mut instance_name);
462         Some(StatRecorder::new(cx, instance_name))
463     } else {
464         None
465     };
466
467     // this is an info! to allow collecting monomorphization statistics
468     // and to allow finding the last function before LLVM aborts from
469     // release builds.
470     info!("trans_instance({})", instance);
471
472     let fn_ty = instance.ty(cx.tcx);
473     let sig = common::ty_fn_sig(cx, fn_ty);
474     let sig = cx.tcx.erase_late_bound_regions_and_normalize(&sig);
475
476     let lldecl = match cx.instances.borrow().get(&instance) {
477         Some(&val) => val,
478         None => bug!("Instance `{:?}` not already declared", instance)
479     };
480
481     cx.stats.borrow_mut().n_closures += 1;
482
483     // The `uwtable` attribute according to LLVM is:
484     //
485     //     This attribute indicates that the ABI being targeted requires that an
486     //     unwind table entry be produced for this function even if we can show
487     //     that no exceptions passes by it. This is normally the case for the
488     //     ELF x86-64 abi, but it can be disabled for some compilation units.
489     //
490     // Typically when we're compiling with `-C panic=abort` (which implies this
491     // `no_landing_pads` check) we don't need `uwtable` because we can't
492     // generate any exceptions! On Windows, however, exceptions include other
493     // events such as illegal instructions, segfaults, etc. This means that on
494     // Windows we end up still needing the `uwtable` attribute even if the `-C
495     // panic=abort` flag is passed.
496     //
497     // You can also find more info on why Windows is whitelisted here in:
498     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
499     if !cx.sess().no_landing_pads() ||
500        cx.sess().target.target.options.is_like_windows {
501         attributes::emit_uwtable(lldecl, true);
502     }
503
504     let mir = cx.tcx.instance_mir(instance.def);
505     mir::trans_mir(cx, lldecl, &mir, instance, sig);
506 }
507
508 pub fn set_link_section(cx: &CodegenCx,
509                         llval: ValueRef,
510                         attrs: &[ast::Attribute]) {
511     if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
512         if contains_null(&sect.as_str()) {
513             cx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
514         }
515         unsafe {
516             let buf = CString::new(sect.as_str().as_bytes()).unwrap();
517             llvm::LLVMSetSection(llval, buf.as_ptr());
518         }
519     }
520 }
521
522 /// Create the `main` function which will initialize the rust runtime and call
523 /// users main function.
524 fn maybe_create_entry_wrapper(cx: &CodegenCx) {
525     let (main_def_id, span) = match *cx.sess().entry_fn.borrow() {
526         Some((id, span)) => {
527             (cx.tcx.hir.local_def_id(id), span)
528         }
529         None => return,
530     };
531
532     let instance = Instance::mono(cx.tcx, main_def_id);
533
534     if !cx.codegen_unit.contains_item(&MonoItem::Fn(instance)) {
535         // We want to create the wrapper in the same codegen unit as Rust's main
536         // function.
537         return;
538     }
539
540     let main_llfn = callee::get_fn(cx, instance);
541
542     let et = cx.sess().entry_type.get().unwrap();
543     match et {
544         config::EntryMain => create_entry_fn(cx, span, main_llfn, main_def_id, true),
545         config::EntryStart => create_entry_fn(cx, span, main_llfn, main_def_id, false),
546         config::EntryNone => {}    // Do nothing.
547     }
548
549     fn create_entry_fn<'cx>(cx: &'cx CodegenCx,
550                        sp: Span,
551                        rust_main: ValueRef,
552                        rust_main_def_id: DefId,
553                        use_start_lang_item: bool) {
554         let llfty = Type::func(&[Type::c_int(cx), Type::i8p(cx).ptr_to()], &Type::c_int(cx));
555
556         let main_ret_ty = cx.tcx.fn_sig(rust_main_def_id).output();
557         // Given that `main()` has no arguments,
558         // then its return type cannot have
559         // late-bound regions, since late-bound
560         // regions must appear in the argument
561         // listing.
562         let main_ret_ty = main_ret_ty.no_late_bound_regions().unwrap();
563
564         if declare::get_defined_value(cx, "main").is_some() {
565             // FIXME: We should be smart and show a better diagnostic here.
566             cx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
567                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
568                       .emit();
569             cx.sess().abort_if_errors();
570             bug!();
571         }
572         let llfn = declare::declare_cfn(cx, "main", llfty);
573
574         // `main` should respect same config for frame pointer elimination as rest of code
575         attributes::set_frame_pointer_elimination(cx, llfn);
576
577         let bx = Builder::new_block(cx, llfn, "top");
578
579         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(&bx);
580
581         // Params from native main() used as args for rust start function
582         let param_argc = get_param(llfn, 0);
583         let param_argv = get_param(llfn, 1);
584         let arg_argc = bx.intcast(param_argc, cx.isize_ty, true);
585         let arg_argv = param_argv;
586
587         let (start_fn, args) = if use_start_lang_item {
588             let start_def_id = cx.tcx.require_lang_item(StartFnLangItem);
589             let start_fn = callee::resolve_and_get_fn(cx, start_def_id, cx.tcx.mk_substs(
590                 iter::once(Kind::from(main_ret_ty))));
591             (start_fn, vec![bx.pointercast(rust_main, Type::i8p(cx).ptr_to()),
592                             arg_argc, arg_argv])
593         } else {
594             debug!("using user-defined start fn");
595             (rust_main, vec![arg_argc, arg_argv])
596         };
597
598         let result = bx.call(start_fn, &args, None);
599         bx.ret(bx.intcast(result, Type::c_int(cx), true));
600     }
601 }
602
603 fn contains_null(s: &str) -> bool {
604     s.bytes().any(|b| b == 0)
605 }
606
607 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
608                             llmod_id: &str,
609                             link_meta: &LinkMeta,
610                             exported_symbols: &NodeSet)
611                             -> (ContextRef, ModuleRef, EncodedMetadata) {
612     use std::io::Write;
613     use flate2::Compression;
614     use flate2::write::DeflateEncoder;
615
616     let (metadata_llcx, metadata_llmod) = unsafe {
617         context::create_context_and_module(tcx.sess, llmod_id)
618     };
619
620     #[derive(PartialEq, Eq, PartialOrd, Ord)]
621     enum MetadataKind {
622         None,
623         Uncompressed,
624         Compressed
625     }
626
627     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
628         match *ty {
629             config::CrateTypeExecutable |
630             config::CrateTypeStaticlib |
631             config::CrateTypeCdylib => MetadataKind::None,
632
633             config::CrateTypeRlib => MetadataKind::Uncompressed,
634
635             config::CrateTypeDylib |
636             config::CrateTypeProcMacro => MetadataKind::Compressed,
637         }
638     }).max().unwrap();
639
640     if kind == MetadataKind::None {
641         return (metadata_llcx,
642                 metadata_llmod,
643                 EncodedMetadata::new());
644     }
645
646     let metadata = tcx.encode_metadata(link_meta, exported_symbols);
647     if kind == MetadataKind::Uncompressed {
648         return (metadata_llcx, metadata_llmod, metadata);
649     }
650
651     assert!(kind == MetadataKind::Compressed);
652     let mut compressed = tcx.metadata_encoding_version();
653     DeflateEncoder::new(&mut compressed, Compression::fast())
654         .write_all(&metadata.raw_data).unwrap();
655
656     let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
657     let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
658     let name = symbol_export::metadata_symbol_name(tcx);
659     let buf = CString::new(name).unwrap();
660     let llglobal = unsafe {
661         llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
662     };
663     unsafe {
664         llvm::LLVMSetInitializer(llglobal, llconst);
665         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
666         let name = CString::new(section_name).unwrap();
667         llvm::LLVMSetSection(llglobal, name.as_ptr());
668
669         // Also generate a .section directive to force no
670         // flags, at least for ELF outputs, so that the
671         // metadata doesn't get loaded into memory.
672         let directive = format!(".section {}", section_name);
673         let directive = CString::new(directive).unwrap();
674         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
675     }
676     return (metadata_llcx, metadata_llmod, metadata);
677 }
678
679 pub struct ValueIter {
680     cur: ValueRef,
681     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
682 }
683
684 impl Iterator for ValueIter {
685     type Item = ValueRef;
686
687     fn next(&mut self) -> Option<ValueRef> {
688         let old = self.cur;
689         if !old.is_null() {
690             self.cur = unsafe { (self.step)(old) };
691             Some(old)
692         } else {
693             None
694         }
695     }
696 }
697
698 pub fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
699     unsafe {
700         ValueIter {
701             cur: llvm::LLVMGetFirstGlobal(llmod),
702             step: llvm::LLVMGetNextGlobal,
703         }
704     }
705 }
706
707 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
708                              rx: mpsc::Receiver<Box<Any + Send>>)
709                              -> OngoingCrateTranslation {
710
711     check_for_rustc_errors_attr(tcx);
712
713     if let Some(true) = tcx.sess.opts.debugging_opts.thinlto {
714         if unsafe { !llvm::LLVMRustThinLTOAvailable() } {
715             tcx.sess.fatal("this compiler's LLVM does not support ThinLTO");
716         }
717     }
718
719     let crate_hash = tcx.crate_hash(LOCAL_CRATE);
720     let link_meta = link::build_link_meta(crate_hash);
721     let exported_symbol_node_ids = find_exported_symbols(tcx);
722
723     // Translate the metadata.
724     let llmod_id = "metadata";
725     let (metadata_llcx, metadata_llmod, metadata) =
726         time(tcx.sess.time_passes(), "write metadata", || {
727             write_metadata(tcx, llmod_id, &link_meta, &exported_symbol_node_ids)
728         });
729
730     let metadata_module = ModuleTranslation {
731         name: link::METADATA_MODULE_NAME.to_string(),
732         llmod_id: llmod_id.to_string(),
733         source: ModuleSource::Translated(ModuleLlvm {
734             llcx: metadata_llcx,
735             llmod: metadata_llmod,
736             tm: create_target_machine(tcx.sess),
737         }),
738         kind: ModuleKind::Metadata,
739     };
740
741     let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
742         Some(time_graph::TimeGraph::new())
743     } else {
744         None
745     };
746
747     // Skip crate items and just output metadata in -Z no-trans mode.
748     if tcx.sess.opts.debugging_opts.no_trans ||
749        !tcx.sess.opts.output_types.should_trans() {
750         let ongoing_translation = write::start_async_translation(
751             tcx,
752             time_graph.clone(),
753             link_meta,
754             metadata,
755             rx,
756             1);
757
758         ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
759         ongoing_translation.translation_finished(tcx);
760
761         assert_and_save_dep_graph(tcx);
762
763         ongoing_translation.check_for_errors(tcx.sess);
764
765         return ongoing_translation;
766     }
767
768     // Run the translation item collector and partition the collected items into
769     // codegen units.
770     let codegen_units =
771         tcx.collect_and_partition_translation_items(LOCAL_CRATE).1;
772     let codegen_units = (*codegen_units).clone();
773
774     // Force all codegen_unit queries so they are already either red or green
775     // when compile_codegen_unit accesses them. We are not able to re-execute
776     // the codegen_unit query from just the DepNode, so an unknown color would
777     // lead to having to re-execute compile_codegen_unit, possibly
778     // unnecessarily.
779     if tcx.dep_graph.is_fully_enabled() {
780         for cgu in &codegen_units {
781             tcx.codegen_unit(cgu.name().clone());
782         }
783     }
784
785     let ongoing_translation = write::start_async_translation(
786         tcx,
787         time_graph.clone(),
788         link_meta,
789         metadata,
790         rx,
791         codegen_units.len());
792
793     // Translate an allocator shim, if any
794     let allocator_module = if let Some(kind) = tcx.sess.allocator_kind.get() {
795         unsafe {
796             let llmod_id = "allocator";
797             let (llcx, llmod) =
798                 context::create_context_and_module(tcx.sess, llmod_id);
799             let modules = ModuleLlvm {
800                 llmod,
801                 llcx,
802                 tm: create_target_machine(tcx.sess),
803             };
804             time(tcx.sess.time_passes(), "write allocator module", || {
805                 allocator::trans(tcx, &modules, kind)
806             });
807
808             Some(ModuleTranslation {
809                 name: link::ALLOCATOR_MODULE_NAME.to_string(),
810                 llmod_id: llmod_id.to_string(),
811                 source: ModuleSource::Translated(modules),
812                 kind: ModuleKind::Allocator,
813             })
814         }
815     } else {
816         None
817     };
818
819     if let Some(allocator_module) = allocator_module {
820         ongoing_translation.submit_pre_translated_module_to_llvm(tcx, allocator_module);
821     }
822
823     ongoing_translation.submit_pre_translated_module_to_llvm(tcx, metadata_module);
824
825     // We sort the codegen units by size. This way we can schedule work for LLVM
826     // a bit more efficiently.
827     let codegen_units = {
828         let mut codegen_units = codegen_units;
829         codegen_units.sort_by_key(|cgu| usize::MAX - cgu.size_estimate());
830         codegen_units
831     };
832
833     let mut total_trans_time = Duration::new(0, 0);
834     let mut all_stats = Stats::default();
835
836     for cgu in codegen_units.into_iter() {
837         ongoing_translation.wait_for_signal_to_translate_item();
838         ongoing_translation.check_for_errors(tcx.sess);
839
840         // First, if incremental compilation is enabled, we try to re-use the
841         // codegen unit from the cache.
842         if tcx.dep_graph.is_fully_enabled() {
843             let cgu_id = cgu.work_product_id();
844
845             // Check whether there is a previous work-product we can
846             // re-use.  Not only must the file exist, and the inputs not
847             // be dirty, but the hash of the symbols we will generate must
848             // be the same.
849             if let Some(buf) = tcx.dep_graph.previous_work_product(&cgu_id) {
850                 let dep_node = &DepNode::new(tcx,
851                     DepConstructor::CompileCodegenUnit(cgu.name().clone()));
852
853                 // We try to mark the DepNode::CompileCodegenUnit green. If we
854                 // succeed it means that none of the dependencies has changed
855                 // and we can safely re-use.
856                 if let Some(dep_node_index) = tcx.dep_graph.try_mark_green(tcx, dep_node) {
857                     // Append ".rs" to LLVM module identifier.
858                     //
859                     // LLVM code generator emits a ".file filename" directive
860                     // for ELF backends. Value of the "filename" is set as the
861                     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
862                     // crashes if the module identifier is same as other symbols
863                     // such as a function name in the module.
864                     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
865                     let llmod_id = format!("{}.rs", cgu.name());
866
867                     let module = ModuleTranslation {
868                         name: cgu.name().to_string(),
869                         source: ModuleSource::Preexisting(buf),
870                         kind: ModuleKind::Regular,
871                         llmod_id,
872                     };
873                     tcx.dep_graph.mark_loaded_from_cache(dep_node_index, true);
874                     write::submit_translated_module_to_llvm(tcx, module, 0);
875                     // Continue to next cgu, this one is done.
876                     continue
877                 }
878             } else {
879                 // This can happen if files were  deleted from the cache
880                 // directory for some reason. We just re-compile then.
881             }
882         }
883
884         let _timing_guard = time_graph.as_ref().map(|time_graph| {
885             time_graph.start(write::TRANS_WORKER_TIMELINE,
886                              write::TRANS_WORK_PACKAGE_KIND,
887                              &format!("codegen {}", cgu.name()))
888         });
889         let start_time = Instant::now();
890         all_stats.extend(tcx.compile_codegen_unit(*cgu.name()));
891         total_trans_time += start_time.elapsed();
892         ongoing_translation.check_for_errors(tcx.sess);
893     }
894
895     ongoing_translation.translation_finished(tcx);
896
897     // Since the main thread is sometimes blocked during trans, we keep track
898     // -Ztime-passes output manually.
899     print_time_passes_entry(tcx.sess.time_passes(),
900                             "translate to LLVM IR",
901                             total_trans_time);
902
903     if tcx.sess.opts.incremental.is_some() {
904         ::rustc_incremental::assert_module_sources::assert_module_sources(tcx);
905     }
906
907     symbol_names_test::report_symbol_names(tcx);
908
909     if tcx.sess.trans_stats() {
910         println!("--- trans stats ---");
911         println!("n_glues_created: {}", all_stats.n_glues_created);
912         println!("n_null_glues: {}", all_stats.n_null_glues);
913         println!("n_real_glues: {}", all_stats.n_real_glues);
914
915         println!("n_fns: {}", all_stats.n_fns);
916         println!("n_inlines: {}", all_stats.n_inlines);
917         println!("n_closures: {}", all_stats.n_closures);
918         println!("fn stats:");
919         all_stats.fn_stats.sort_by_key(|&(_, insns)| insns);
920         for &(ref name, insns) in all_stats.fn_stats.iter() {
921             println!("{} insns, {}", insns, *name);
922         }
923     }
924
925     if tcx.sess.count_llvm_insns() {
926         for (k, v) in all_stats.llvm_insns.iter() {
927             println!("{:7} {}", *v, *k);
928         }
929     }
930
931     ongoing_translation.check_for_errors(tcx.sess);
932
933     assert_and_save_dep_graph(tcx);
934     ongoing_translation
935 }
936
937 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
938     time(tcx.sess.time_passes(),
939          "assert dep graph",
940          || rustc_incremental::assert_dep_graph(tcx));
941
942     time(tcx.sess.time_passes(),
943          "serialize dep graph",
944          || rustc_incremental::save_dep_graph(tcx));
945 }
946
947 fn collect_and_partition_translation_items<'a, 'tcx>(
948     tcx: TyCtxt<'a, 'tcx, 'tcx>,
949     cnum: CrateNum,
950 ) -> (Arc<DefIdSet>, Arc<Vec<Arc<CodegenUnit<'tcx>>>>)
951 {
952     assert_eq!(cnum, LOCAL_CRATE);
953     let time_passes = tcx.sess.time_passes();
954
955     let collection_mode = match tcx.sess.opts.debugging_opts.print_trans_items {
956         Some(ref s) => {
957             let mode_string = s.to_lowercase();
958             let mode_string = mode_string.trim();
959             if mode_string == "eager" {
960                 MonoItemCollectionMode::Eager
961             } else {
962                 if mode_string != "lazy" {
963                     let message = format!("Unknown codegen-item collection mode '{}'. \
964                                            Falling back to 'lazy' mode.",
965                                            mode_string);
966                     tcx.sess.warn(&message);
967                 }
968
969                 MonoItemCollectionMode::Lazy
970             }
971         }
972         None => {
973             if tcx.sess.opts.cg.link_dead_code {
974                 MonoItemCollectionMode::Eager
975             } else {
976                 MonoItemCollectionMode::Lazy
977             }
978         }
979     };
980
981     let (items, inlining_map) =
982         time(time_passes, "translation item collection", || {
983             collector::collect_crate_mono_items(tcx, collection_mode)
984     });
985
986     ::rustc_mir::monomorphize::assert_symbols_are_distinct(tcx, items.iter());
987
988     let strategy = if tcx.sess.opts.incremental.is_some() {
989         PartitioningStrategy::PerModule
990     } else {
991         PartitioningStrategy::FixedUnitCount(tcx.sess.codegen_units())
992     };
993
994     let codegen_units = time(time_passes, "codegen unit partitioning", || {
995         partitioning::partition(tcx,
996                                 items.iter().cloned(),
997                                 strategy,
998                                 &inlining_map)
999             .into_iter()
1000             .map(Arc::new)
1001             .collect::<Vec<_>>()
1002     });
1003
1004     let translation_items: DefIdSet = items.iter().filter_map(|trans_item| {
1005         match *trans_item {
1006             MonoItem::Fn(ref instance) => Some(instance.def_id()),
1007             MonoItem::Static(def_id) => Some(def_id),
1008             _ => None,
1009         }
1010     }).collect();
1011
1012     if tcx.sess.opts.debugging_opts.print_trans_items.is_some() {
1013         let mut item_to_cgus = FxHashMap();
1014
1015         for cgu in &codegen_units {
1016             for (&trans_item, &linkage) in cgu.items() {
1017                 item_to_cgus.entry(trans_item)
1018                             .or_insert(Vec::new())
1019                             .push((cgu.name().clone(), linkage));
1020             }
1021         }
1022
1023         let mut item_keys: Vec<_> = items
1024             .iter()
1025             .map(|i| {
1026                 let mut output = i.to_string(tcx);
1027                 output.push_str(" @@");
1028                 let mut empty = Vec::new();
1029                 let cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1030                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1031                 cgus.dedup();
1032                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1033                     output.push_str(" ");
1034                     output.push_str(&cgu_name);
1035
1036                     let linkage_abbrev = match linkage {
1037                         Linkage::External => "External",
1038                         Linkage::AvailableExternally => "Available",
1039                         Linkage::LinkOnceAny => "OnceAny",
1040                         Linkage::LinkOnceODR => "OnceODR",
1041                         Linkage::WeakAny => "WeakAny",
1042                         Linkage::WeakODR => "WeakODR",
1043                         Linkage::Appending => "Appending",
1044                         Linkage::Internal => "Internal",
1045                         Linkage::Private => "Private",
1046                         Linkage::ExternalWeak => "ExternalWeak",
1047                         Linkage::Common => "Common",
1048                     };
1049
1050                     output.push_str("[");
1051                     output.push_str(linkage_abbrev);
1052                     output.push_str("]");
1053                 }
1054                 output
1055             })
1056             .collect();
1057
1058         item_keys.sort();
1059
1060         for item in item_keys {
1061             println!("TRANS_ITEM {}", item);
1062         }
1063     }
1064
1065     (Arc::new(translation_items), Arc::new(codegen_units))
1066 }
1067
1068 impl CrateInfo {
1069     pub fn new(tcx: TyCtxt) -> CrateInfo {
1070         let mut info = CrateInfo {
1071             panic_runtime: None,
1072             compiler_builtins: None,
1073             profiler_runtime: None,
1074             sanitizer_runtime: None,
1075             is_no_builtins: FxHashSet(),
1076             native_libraries: FxHashMap(),
1077             used_libraries: tcx.native_libraries(LOCAL_CRATE),
1078             link_args: tcx.link_args(LOCAL_CRATE),
1079             crate_name: FxHashMap(),
1080             used_crates_dynamic: cstore::used_crates(tcx, LinkagePreference::RequireDynamic),
1081             used_crates_static: cstore::used_crates(tcx, LinkagePreference::RequireStatic),
1082             used_crate_source: FxHashMap(),
1083         };
1084
1085         for &cnum in tcx.crates().iter() {
1086             info.native_libraries.insert(cnum, tcx.native_libraries(cnum));
1087             info.crate_name.insert(cnum, tcx.crate_name(cnum).to_string());
1088             info.used_crate_source.insert(cnum, tcx.used_crate_source(cnum));
1089             if tcx.is_panic_runtime(cnum) {
1090                 info.panic_runtime = Some(cnum);
1091             }
1092             if tcx.is_compiler_builtins(cnum) {
1093                 info.compiler_builtins = Some(cnum);
1094             }
1095             if tcx.is_profiler_runtime(cnum) {
1096                 info.profiler_runtime = Some(cnum);
1097             }
1098             if tcx.is_sanitizer_runtime(cnum) {
1099                 info.sanitizer_runtime = Some(cnum);
1100             }
1101             if tcx.is_no_builtins(cnum) {
1102                 info.is_no_builtins.insert(cnum);
1103             }
1104         }
1105
1106
1107         return info
1108     }
1109 }
1110
1111 fn is_translated_item(tcx: TyCtxt, id: DefId) -> bool {
1112     let (all_trans_items, _) =
1113         tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1114     all_trans_items.contains(&id)
1115 }
1116
1117 fn compile_codegen_unit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1118                                   cgu: InternedString) -> Stats {
1119     let cgu = tcx.codegen_unit(cgu);
1120
1121     let start_time = Instant::now();
1122     let (stats, module) = module_translation(tcx, cgu);
1123     let time_to_translate = start_time.elapsed();
1124
1125     // We assume that the cost to run LLVM on a CGU is proportional to
1126     // the time we needed for translating it.
1127     let cost = time_to_translate.as_secs() * 1_000_000_000 +
1128                time_to_translate.subsec_nanos() as u64;
1129
1130     write::submit_translated_module_to_llvm(tcx,
1131                                             module,
1132                                             cost);
1133     return stats;
1134
1135     fn module_translation<'a, 'tcx>(
1136         tcx: TyCtxt<'a, 'tcx, 'tcx>,
1137         cgu: Arc<CodegenUnit<'tcx>>)
1138         -> (Stats, ModuleTranslation)
1139     {
1140         let cgu_name = cgu.name().to_string();
1141
1142         // Append ".rs" to LLVM module identifier.
1143         //
1144         // LLVM code generator emits a ".file filename" directive
1145         // for ELF backends. Value of the "filename" is set as the
1146         // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
1147         // crashes if the module identifier is same as other symbols
1148         // such as a function name in the module.
1149         // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
1150         let llmod_id = format!("{}-{}.rs",
1151                                cgu.name(),
1152                                tcx.crate_disambiguator(LOCAL_CRATE)
1153                                    .to_fingerprint().to_hex());
1154
1155         // Instantiate translation items without filling out definitions yet...
1156         let cx = CodegenCx::new(tcx, cgu, &llmod_id);
1157         let module = {
1158             let trans_items = cx.codegen_unit
1159                                  .items_in_deterministic_order(cx.tcx);
1160             for &(trans_item, (linkage, visibility)) in &trans_items {
1161                 trans_item.predefine(&cx, linkage, visibility);
1162             }
1163
1164             // ... and now that we have everything pre-defined, fill out those definitions.
1165             for &(trans_item, _) in &trans_items {
1166                 trans_item.define(&cx);
1167             }
1168
1169             // If this codegen unit contains the main function, also create the
1170             // wrapper here
1171             maybe_create_entry_wrapper(&cx);
1172
1173             // Run replace-all-uses-with for statics that need it
1174             for &(old_g, new_g) in cx.statics_to_rauw.borrow().iter() {
1175                 unsafe {
1176                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1177                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1178                     llvm::LLVMDeleteGlobal(old_g);
1179                 }
1180             }
1181
1182             // Create the llvm.used variable
1183             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1184             if !cx.used_statics.borrow().is_empty() {
1185                 let name = CString::new("llvm.used").unwrap();
1186                 let section = CString::new("llvm.metadata").unwrap();
1187                 let array = C_array(Type::i8(&cx).ptr_to(), &*cx.used_statics.borrow());
1188
1189                 unsafe {
1190                     let g = llvm::LLVMAddGlobal(cx.llmod,
1191                                                 val_ty(array).to_ref(),
1192                                                 name.as_ptr());
1193                     llvm::LLVMSetInitializer(g, array);
1194                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1195                     llvm::LLVMSetSection(g, section.as_ptr());
1196                 }
1197             }
1198
1199             // Finalize debuginfo
1200             if cx.sess().opts.debuginfo != NoDebugInfo {
1201                 debuginfo::finalize(&cx);
1202             }
1203
1204             let llvm_module = ModuleLlvm {
1205                 llcx: cx.llcx,
1206                 llmod: cx.llmod,
1207                 tm: create_target_machine(cx.sess()),
1208             };
1209
1210             ModuleTranslation {
1211                 name: cgu_name,
1212                 source: ModuleSource::Translated(llvm_module),
1213                 kind: ModuleKind::Regular,
1214                 llmod_id,
1215             }
1216         };
1217
1218         (cx.into_stats(), module)
1219     }
1220 }
1221
1222 pub fn provide(providers: &mut Providers) {
1223     providers.collect_and_partition_translation_items =
1224         collect_and_partition_translation_items;
1225
1226     providers.is_translated_item = is_translated_item;
1227
1228     providers.codegen_unit = |tcx, name| {
1229         let (_, all) = tcx.collect_and_partition_translation_items(LOCAL_CRATE);
1230         all.iter()
1231             .find(|cgu| *cgu.name() == name)
1232             .cloned()
1233             .expect(&format!("failed to find cgu with name {:?}", name))
1234     };
1235     providers.compile_codegen_unit = compile_codegen_unit;
1236 }
1237
1238 pub fn linkage_to_llvm(linkage: Linkage) -> llvm::Linkage {
1239     match linkage {
1240         Linkage::External => llvm::Linkage::ExternalLinkage,
1241         Linkage::AvailableExternally => llvm::Linkage::AvailableExternallyLinkage,
1242         Linkage::LinkOnceAny => llvm::Linkage::LinkOnceAnyLinkage,
1243         Linkage::LinkOnceODR => llvm::Linkage::LinkOnceODRLinkage,
1244         Linkage::WeakAny => llvm::Linkage::WeakAnyLinkage,
1245         Linkage::WeakODR => llvm::Linkage::WeakODRLinkage,
1246         Linkage::Appending => llvm::Linkage::AppendingLinkage,
1247         Linkage::Internal => llvm::Linkage::InternalLinkage,
1248         Linkage::Private => llvm::Linkage::PrivateLinkage,
1249         Linkage::ExternalWeak => llvm::Linkage::ExternalWeakLinkage,
1250         Linkage::Common => llvm::Linkage::CommonLinkage,
1251     }
1252 }
1253
1254 pub fn visibility_to_llvm(linkage: Visibility) -> llvm::Visibility {
1255     match linkage {
1256         Visibility::Default => llvm::Visibility::Default,
1257         Visibility::Hidden => llvm::Visibility::Hidden,
1258         Visibility::Protected => llvm::Visibility::Protected,
1259     }
1260 }
1261
1262 // FIXME(mw): Anything that is produced via DepGraph::with_task() must implement
1263 //            the HashStable trait. Normally DepGraph::with_task() calls are
1264 //            hidden behind queries, but CGU creation is a special case in two
1265 //            ways: (1) it's not a query and (2) CGU are output nodes, so their
1266 //            Fingerprints are not actually needed. It remains to be clarified
1267 //            how exactly this case will be handled in the red/green system but
1268 //            for now we content ourselves with providing a no-op HashStable
1269 //            implementation for CGUs.
1270 mod temp_stable_hash_impls {
1271     use rustc_data_structures::stable_hasher::{StableHasherResult, StableHasher,
1272                                                HashStable};
1273     use ModuleTranslation;
1274
1275     impl<HCX> HashStable<HCX> for ModuleTranslation {
1276         fn hash_stable<W: StableHasherResult>(&self,
1277                                               _: &mut HCX,
1278                                               _: &mut StableHasher<W>) {
1279             // do nothing
1280         }
1281     }
1282 }