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