]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
14c73de64bc798f80e82768dac05c2f1956ea6fa
[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 assert_module_sources;
32 use back::link;
33 use back::linker::LinkerInfo;
34 use back::symbol_export::{self, ExportedSymbols};
35 use back::write::{self, OngoingCrateTranslation};
36 use llvm::{ContextRef, Linkage, ModuleRef, ValueRef, Vector, get_param};
37 use llvm;
38 use metadata;
39 use rustc::hir::def_id::LOCAL_CRATE;
40 use rustc::middle::lang_items::StartFnLangItem;
41 use rustc::middle::cstore::{EncodedMetadata, EncodedMetadataHashes};
42 use rustc::ty::{self, Ty, TyCtxt};
43 use rustc::dep_graph::AssertDepGraphSafe;
44 use rustc::middle::cstore::LinkMeta;
45 use rustc::hir::map as hir_map;
46 use rustc::util::common::{time, print_time_passes_entry};
47 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType};
48 use rustc::session::Session;
49 use rustc_incremental::{self, IncrementalHashesMap};
50 use abi;
51 use allocator;
52 use mir::lvalue::LvalueRef;
53 use attributes;
54 use builder::Builder;
55 use callee;
56 use common::{C_bool, C_bytes_in_context, C_i32, C_uint};
57 use collector::{self, TransItemCollectionMode};
58 use common::{C_struct_in_context, C_u64, C_undef, C_array};
59 use common::CrateContext;
60 use common::{type_is_zero_size, val_ty};
61 use common;
62 use consts;
63 use context::{self, LocalCrateContext, SharedCrateContext, Stats};
64 use debuginfo;
65 use declare;
66 use machine;
67 use meth;
68 use mir;
69 use monomorphize::{self, Instance};
70 use partitioning::{self, PartitioningStrategy, CodegenUnit};
71 use symbol_names_test;
72 use time_graph;
73 use trans_item::{TransItem, DefPathBasedNames};
74 use type_::Type;
75 use type_of;
76 use value::Value;
77 use rustc::util::nodemap::{NodeSet, FxHashMap, FxHashSet};
78
79 use libc::c_uint;
80 use std::ffi::{CStr, CString};
81 use std::str;
82 use std::sync::Arc;
83 use std::time::{Instant, Duration};
84 use std::i32;
85 use syntax_pos::Span;
86 use syntax::attr;
87 use rustc::hir;
88 use syntax::ast;
89
90 use mir::lvalue::Alignment;
91
92 pub struct StatRecorder<'a, 'tcx: 'a> {
93     ccx: &'a CrateContext<'a, 'tcx>,
94     name: Option<String>,
95     istart: usize,
96 }
97
98 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
99     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
100         let istart = ccx.stats().n_llvm_insns.get();
101         StatRecorder {
102             ccx: ccx,
103             name: Some(name),
104             istart: istart,
105         }
106     }
107 }
108
109 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
110     fn drop(&mut self) {
111         if self.ccx.sess().trans_stats() {
112             let iend = self.ccx.stats().n_llvm_insns.get();
113             self.ccx.stats().fn_stats.borrow_mut()
114                 .push((self.name.take().unwrap(), iend - self.istart));
115             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
116             // Reset LLVM insn count to avoid compound costs.
117             self.ccx.stats().n_llvm_insns.set(self.istart);
118         }
119     }
120 }
121
122 pub fn get_meta(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
123     bcx.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
124 }
125
126 pub fn get_dataptr(bcx: &Builder, fat_ptr: ValueRef) -> ValueRef {
127     bcx.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
128 }
129
130 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
131                                 signed: bool)
132                                 -> llvm::IntPredicate {
133     match op {
134         hir::BiEq => llvm::IntEQ,
135         hir::BiNe => llvm::IntNE,
136         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
137         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
138         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
139         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
140         op => {
141             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
142                   found {:?}",
143                  op)
144         }
145     }
146 }
147
148 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
149     match op {
150         hir::BiEq => llvm::RealOEQ,
151         hir::BiNe => llvm::RealUNE,
152         hir::BiLt => llvm::RealOLT,
153         hir::BiLe => llvm::RealOLE,
154         hir::BiGt => llvm::RealOGT,
155         hir::BiGe => llvm::RealOGE,
156         op => {
157             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
158                   found {:?}",
159                  op);
160         }
161     }
162 }
163
164 pub fn compare_simd_types<'a, 'tcx>(
165     bcx: &Builder<'a, 'tcx>,
166     lhs: ValueRef,
167     rhs: ValueRef,
168     t: Ty<'tcx>,
169     ret_ty: Type,
170     op: hir::BinOp_
171 ) -> ValueRef {
172     let signed = match t.sty {
173         ty::TyFloat(_) => {
174             let cmp = bin_op_to_fcmp_predicate(op);
175             return bcx.sext(bcx.fcmp(cmp, lhs, rhs), ret_ty);
176         },
177         ty::TyUint(_) => false,
178         ty::TyInt(_) => true,
179         _ => bug!("compare_simd_types: invalid SIMD type"),
180     };
181
182     let cmp = bin_op_to_icmp_predicate(op, signed);
183     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
184     // to get the correctly sized type. This will compile to a single instruction
185     // once the IR is converted to assembly if the SIMD instruction is supported
186     // by the target architecture.
187     bcx.sext(bcx.icmp(cmp, lhs, rhs), ret_ty)
188 }
189
190 /// Retrieve the information we are losing (making dynamic) in an unsizing
191 /// adjustment.
192 ///
193 /// The `old_info` argument is a bit funny. It is intended for use
194 /// in an upcast, where the new vtable for an object will be drived
195 /// from the old one.
196 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
197                                 source: Ty<'tcx>,
198                                 target: Ty<'tcx>,
199                                 old_info: Option<ValueRef>)
200                                 -> ValueRef {
201     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
202     match (&source.sty, &target.sty) {
203         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
204         (&ty::TyDynamic(..), &ty::TyDynamic(..)) => {
205             // For now, upcasts are limited to changes in marker
206             // traits, and hence never actually require an actual
207             // change to the vtable.
208             old_info.expect("unsized_info: missing old info for trait upcast")
209         }
210         (_, &ty::TyDynamic(ref data, ..)) => {
211             consts::ptrcast(meth::get_vtable(ccx, source, data.principal()),
212                             Type::vtable_ptr(ccx))
213         }
214         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
215                                      source,
216                                      target),
217     }
218 }
219
220 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
221 pub fn unsize_thin_ptr<'a, 'tcx>(
222     bcx: &Builder<'a, 'tcx>,
223     src: ValueRef,
224     src_ty: Ty<'tcx>,
225     dst_ty: Ty<'tcx>
226 ) -> (ValueRef, ValueRef) {
227     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
228     match (&src_ty.sty, &dst_ty.sty) {
229         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
230          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
231         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
232          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
233         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
234          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
235             assert!(bcx.ccx.shared().type_is_sized(a));
236             let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
237             (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
238         }
239         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
240             let (a, b) = (src_ty.boxed_ty(), dst_ty.boxed_ty());
241             assert!(bcx.ccx.shared().type_is_sized(a));
242             let ptr_ty = type_of::in_memory_type_of(bcx.ccx, b).ptr_to();
243             (bcx.pointercast(src, ptr_ty), unsized_info(bcx.ccx, a, b, None))
244         }
245         _ => bug!("unsize_thin_ptr: called on bad types"),
246     }
247 }
248
249 /// Coerce `src`, which is a reference to a value of type `src_ty`,
250 /// to a value of type `dst_ty` and store the result in `dst`
251 pub fn coerce_unsized_into<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
252                                      src: &LvalueRef<'tcx>,
253                                      dst: &LvalueRef<'tcx>) {
254     let src_ty = src.ty.to_ty(bcx.tcx());
255     let dst_ty = dst.ty.to_ty(bcx.tcx());
256     let coerce_ptr = || {
257         let (base, info) = if common::type_is_fat_ptr(bcx.ccx, src_ty) {
258             // fat-ptr to fat-ptr unsize preserves the vtable
259             // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
260             // So we need to pointercast the base to ensure
261             // the types match up.
262             let (base, info) = load_fat_ptr(bcx, src.llval, src.alignment, src_ty);
263             let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx, dst_ty);
264             let base = bcx.pointercast(base, llcast_ty);
265             (base, info)
266         } else {
267             let base = load_ty(bcx, src.llval, src.alignment, src_ty);
268             unsize_thin_ptr(bcx, base, src_ty, dst_ty)
269         };
270         store_fat_ptr(bcx, base, info, dst.llval, dst.alignment, dst_ty);
271     };
272     match (&src_ty.sty, &dst_ty.sty) {
273         (&ty::TyRef(..), &ty::TyRef(..)) |
274         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
275         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
276             coerce_ptr()
277         }
278         (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
279             coerce_ptr()
280         }
281
282         (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
283             assert_eq!(def_a, def_b);
284
285             let src_fields = def_a.variants[0].fields.iter().map(|f| {
286                 monomorphize::field_ty(bcx.tcx(), substs_a, f)
287             });
288             let dst_fields = def_b.variants[0].fields.iter().map(|f| {
289                 monomorphize::field_ty(bcx.tcx(), substs_b, f)
290             });
291
292             let iter = src_fields.zip(dst_fields).enumerate();
293             for (i, (src_fty, dst_fty)) in iter {
294                 if type_is_zero_size(bcx.ccx, dst_fty) {
295                     continue;
296                 }
297
298                 let (src_f, src_f_align) = src.trans_field_ptr(bcx, i);
299                 let (dst_f, dst_f_align) = dst.trans_field_ptr(bcx, i);
300                 if src_fty == dst_fty {
301                     memcpy_ty(bcx, dst_f, src_f, src_fty, None);
302                 } else {
303                     coerce_unsized_into(
304                         bcx,
305                         &LvalueRef::new_sized_ty(src_f, src_fty, src_f_align),
306                         &LvalueRef::new_sized_ty(dst_f, dst_fty, dst_f_align)
307                     );
308                 }
309             }
310         }
311         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
312                   src_ty,
313                   dst_ty),
314     }
315 }
316
317 pub fn cast_shift_expr_rhs(
318     cx: &Builder, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef
319 ) -> ValueRef {
320     cast_shift_rhs(op, lhs, rhs, |a, b| cx.trunc(a, b), |a, b| cx.zext(a, b))
321 }
322
323 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
324     cast_shift_rhs(op,
325                    lhs,
326                    rhs,
327                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
328                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
329 }
330
331 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
332                         lhs: ValueRef,
333                         rhs: ValueRef,
334                         trunc: F,
335                         zext: G)
336                         -> ValueRef
337     where F: FnOnce(ValueRef, Type) -> ValueRef,
338           G: FnOnce(ValueRef, Type) -> ValueRef
339 {
340     // Shifts may have any size int on the rhs
341     if op.is_shift() {
342         let mut rhs_llty = val_ty(rhs);
343         let mut lhs_llty = val_ty(lhs);
344         if rhs_llty.kind() == Vector {
345             rhs_llty = rhs_llty.element_type()
346         }
347         if lhs_llty.kind() == Vector {
348             lhs_llty = lhs_llty.element_type()
349         }
350         let rhs_sz = rhs_llty.int_width();
351         let lhs_sz = lhs_llty.int_width();
352         if lhs_sz < rhs_sz {
353             trunc(rhs, lhs_llty)
354         } else if lhs_sz > rhs_sz {
355             // FIXME (#1877: If shifting by negative
356             // values becomes not undefined then this is wrong.
357             zext(rhs, lhs_llty)
358         } else {
359             rhs
360         }
361     } else {
362         rhs
363     }
364 }
365
366 /// Returns whether this session's target will use SEH-based unwinding.
367 ///
368 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
369 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
370 /// 64-bit MinGW) instead of "full SEH".
371 pub fn wants_msvc_seh(sess: &Session) -> bool {
372     sess.target.target.options.is_like_msvc
373 }
374
375 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
376     let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
377     b.call(assume_intrinsic, &[val], None);
378 }
379
380 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
381 /// differs from the type used for SSA values. Also handles various special cases where the type
382 /// gives us better information about what we are loading.
383 pub fn load_ty<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef,
384                          alignment: Alignment, t: Ty<'tcx>) -> ValueRef {
385     let ccx = b.ccx;
386     if type_is_zero_size(ccx, t) {
387         return C_undef(type_of::type_of(ccx, t));
388     }
389
390     unsafe {
391         let global = llvm::LLVMIsAGlobalVariable(ptr);
392         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
393             let val = llvm::LLVMGetInitializer(global);
394             if !val.is_null() {
395                 if t.is_bool() {
396                     return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
397                 }
398                 return val;
399             }
400         }
401     }
402
403     if t.is_bool() {
404         b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False, alignment.to_align()),
405                 Type::i1(ccx))
406     } else if t.is_char() {
407         // a char is a Unicode codepoint, and so takes values from 0
408         // to 0x10FFFF inclusive only.
409         b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False, alignment.to_align())
410     } else if (t.is_region_ptr() || t.is_box() || t.is_fn())
411         && !common::type_is_fat_ptr(ccx, t)
412     {
413         b.load_nonnull(ptr, alignment.to_align())
414     } else {
415         b.load(ptr, alignment.to_align())
416     }
417 }
418
419 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
420 /// differs from the type used for SSA values.
421 pub fn store_ty<'a, 'tcx>(cx: &Builder<'a, 'tcx>, v: ValueRef, dst: ValueRef,
422                           dst_align: Alignment, t: Ty<'tcx>) {
423     debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
424
425     if common::type_is_fat_ptr(cx.ccx, t) {
426         let lladdr = cx.extract_value(v, abi::FAT_PTR_ADDR);
427         let llextra = cx.extract_value(v, abi::FAT_PTR_EXTRA);
428         store_fat_ptr(cx, lladdr, llextra, dst, dst_align, t);
429     } else {
430         cx.store(from_immediate(cx, v), dst, dst_align.to_align());
431     }
432 }
433
434 pub fn store_fat_ptr<'a, 'tcx>(cx: &Builder<'a, 'tcx>,
435                                data: ValueRef,
436                                extra: ValueRef,
437                                dst: ValueRef,
438                                dst_align: Alignment,
439                                _ty: Ty<'tcx>) {
440     // FIXME: emit metadata
441     cx.store(data, get_dataptr(cx, dst), dst_align.to_align());
442     cx.store(extra, get_meta(cx, dst), dst_align.to_align());
443 }
444
445 pub fn load_fat_ptr<'a, 'tcx>(
446     b: &Builder<'a, 'tcx>, src: ValueRef, alignment: Alignment, t: Ty<'tcx>
447 ) -> (ValueRef, ValueRef) {
448     let ptr = get_dataptr(b, src);
449     let ptr = if t.is_region_ptr() || t.is_box() {
450         b.load_nonnull(ptr, alignment.to_align())
451     } else {
452         b.load(ptr, alignment.to_align())
453     };
454
455     let meta = get_meta(b, src);
456     let meta_ty = val_ty(meta);
457     // If the 'meta' field is a pointer, it's a vtable, so use load_nonnull
458     // instead
459     let meta = if meta_ty.element_type().kind() == llvm::TypeKind::Pointer {
460         b.load_nonnull(meta, None)
461     } else {
462         b.load(meta, None)
463     };
464
465     (ptr, meta)
466 }
467
468 pub fn from_immediate(bcx: &Builder, val: ValueRef) -> ValueRef {
469     if val_ty(val) == Type::i1(bcx.ccx) {
470         bcx.zext(val, Type::i8(bcx.ccx))
471     } else {
472         val
473     }
474 }
475
476 pub fn to_immediate(bcx: &Builder, val: ValueRef, ty: Ty) -> ValueRef {
477     if ty.is_bool() {
478         bcx.trunc(val, Type::i1(bcx.ccx))
479     } else {
480         val
481     }
482 }
483
484 pub enum Lifetime { Start, End }
485
486 impl Lifetime {
487     // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
488     // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
489     // and the intrinsic for `lt` and passes them to `emit`, which is in
490     // charge of generating code to call the passed intrinsic on whatever
491     // block of generated code is targetted for the intrinsic.
492     //
493     // If LLVM lifetime intrinsic support is disabled (i.e.  optimizations
494     // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
495     pub fn call(self, b: &Builder, ptr: ValueRef) {
496         if b.ccx.sess().opts.optimize == config::OptLevel::No {
497             return;
498         }
499
500         let size = machine::llsize_of_alloc(b.ccx, val_ty(ptr).element_type());
501         if size == 0 {
502             return;
503         }
504
505         let lifetime_intrinsic = b.ccx.get_intrinsic(match self {
506             Lifetime::Start => "llvm.lifetime.start",
507             Lifetime::End => "llvm.lifetime.end"
508         });
509
510         let ptr = b.pointercast(ptr, Type::i8p(b.ccx));
511         b.call(lifetime_intrinsic, &[C_u64(b.ccx, size), ptr], None);
512     }
513 }
514
515 pub fn call_memcpy<'a, 'tcx>(b: &Builder<'a, 'tcx>,
516                                dst: ValueRef,
517                                src: ValueRef,
518                                n_bytes: ValueRef,
519                                align: u32) {
520     let ccx = b.ccx;
521     let ptr_width = &ccx.sess().target.target.target_pointer_width;
522     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
523     let memcpy = ccx.get_intrinsic(&key);
524     let src_ptr = b.pointercast(src, Type::i8p(ccx));
525     let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
526     let size = b.intcast(n_bytes, ccx.int_type(), false);
527     let align = C_i32(ccx, align as i32);
528     let volatile = C_bool(ccx, false);
529     b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
530 }
531
532 pub fn memcpy_ty<'a, 'tcx>(
533     bcx: &Builder<'a, 'tcx>,
534     dst: ValueRef,
535     src: ValueRef,
536     t: Ty<'tcx>,
537     align: Option<u32>,
538 ) {
539     let ccx = bcx.ccx;
540
541     let size = ccx.size_of(t);
542     if size == 0 {
543         return;
544     }
545
546     let align = align.unwrap_or_else(|| ccx.align_of(t));
547     call_memcpy(bcx, dst, src, C_uint(ccx, size), align);
548 }
549
550 pub fn call_memset<'a, 'tcx>(b: &Builder<'a, 'tcx>,
551                              ptr: ValueRef,
552                              fill_byte: ValueRef,
553                              size: ValueRef,
554                              align: ValueRef,
555                              volatile: bool) -> ValueRef {
556     let ptr_width = &b.ccx.sess().target.target.target_pointer_width;
557     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
558     let llintrinsicfn = b.ccx.get_intrinsic(&intrinsic_key);
559     let volatile = C_bool(b.ccx, volatile);
560     b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None)
561 }
562
563 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
564     let _s = if ccx.sess().trans_stats() {
565         let mut instance_name = String::new();
566         DefPathBasedNames::new(ccx.tcx(), true, true)
567             .push_def_path(instance.def_id(), &mut instance_name);
568         Some(StatRecorder::new(ccx, instance_name))
569     } else {
570         None
571     };
572
573     // this is an info! to allow collecting monomorphization statistics
574     // and to allow finding the last function before LLVM aborts from
575     // release builds.
576     info!("trans_instance({})", instance);
577
578     let fn_ty = common::instance_ty(ccx.shared(), &instance);
579     let sig = common::ty_fn_sig(ccx, fn_ty);
580     let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
581
582     let lldecl = match ccx.instances().borrow().get(&instance) {
583         Some(&val) => val,
584         None => bug!("Instance `{:?}` not already declared", instance)
585     };
586
587     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
588
589     // The `uwtable` attribute according to LLVM is:
590     //
591     //     This attribute indicates that the ABI being targeted requires that an
592     //     unwind table entry be produced for this function even if we can show
593     //     that no exceptions passes by it. This is normally the case for the
594     //     ELF x86-64 abi, but it can be disabled for some compilation units.
595     //
596     // Typically when we're compiling with `-C panic=abort` (which implies this
597     // `no_landing_pads` check) we don't need `uwtable` because we can't
598     // generate any exceptions! On Windows, however, exceptions include other
599     // events such as illegal instructions, segfaults, etc. This means that on
600     // Windows we end up still needing the `uwtable` attribute even if the `-C
601     // panic=abort` flag is passed.
602     //
603     // You can also find more info on why Windows is whitelisted here in:
604     //      https://bugzilla.mozilla.org/show_bug.cgi?id=1302078
605     if !ccx.sess().no_landing_pads() ||
606        ccx.sess().target.target.options.is_like_windows {
607         attributes::emit_uwtable(lldecl, true);
608     }
609
610     let mir = ccx.tcx().instance_mir(instance.def);
611     mir::trans_mir(ccx, lldecl, &mir, instance, sig);
612 }
613
614 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
615     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
616     // applicable to variable declarations and may not really make sense for
617     // Rust code in the first place but whitelist them anyway and trust that
618     // the user knows what s/he's doing. Who knows, unanticipated use cases
619     // may pop up in the future.
620     //
621     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
622     // and don't have to be, LLVM treats them as no-ops.
623     match name {
624         "appending" => Some(llvm::Linkage::AppendingLinkage),
625         "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
626         "common" => Some(llvm::Linkage::CommonLinkage),
627         "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
628         "external" => Some(llvm::Linkage::ExternalLinkage),
629         "internal" => Some(llvm::Linkage::InternalLinkage),
630         "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
631         "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
632         "private" => Some(llvm::Linkage::PrivateLinkage),
633         "weak" => Some(llvm::Linkage::WeakAnyLinkage),
634         "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
635         _ => None,
636     }
637 }
638
639 pub fn set_link_section(ccx: &CrateContext,
640                         llval: ValueRef,
641                         attrs: &[ast::Attribute]) {
642     if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
643         if contains_null(&sect.as_str()) {
644             ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
645         }
646         unsafe {
647             let buf = CString::new(sect.as_str().as_bytes()).unwrap();
648             llvm::LLVMSetSection(llval, buf.as_ptr());
649         }
650     }
651 }
652
653 // check for the #[rustc_error] annotation, which forces an
654 // error in trans. This is used to write compile-fail tests
655 // that actually test that compilation succeeds without
656 // reporting an error.
657 fn check_for_rustc_errors_attr(tcx: TyCtxt) {
658     if let Some((id, span)) = *tcx.sess.entry_fn.borrow() {
659         let main_def_id = tcx.hir.local_def_id(id);
660
661         if tcx.has_attr(main_def_id, "rustc_error") {
662             tcx.sess.span_fatal(span, "compilation successful");
663         }
664     }
665 }
666
667 /// Create the `main` function which will initialise the rust runtime and call
668 /// users main function.
669 fn maybe_create_entry_wrapper(ccx: &CrateContext) {
670     let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
671         Some((id, span)) => {
672             (ccx.tcx().hir.local_def_id(id), span)
673         }
674         None => return,
675     };
676
677     let instance = Instance::mono(ccx.tcx(), main_def_id);
678
679     if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
680         // We want to create the wrapper in the same codegen unit as Rust's main
681         // function.
682         return;
683     }
684
685     let main_llfn = callee::get_fn(ccx, instance);
686
687     let et = ccx.sess().entry_type.get().unwrap();
688     match et {
689         config::EntryMain => create_entry_fn(ccx, span, main_llfn, true),
690         config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
691         config::EntryNone => {}    // Do nothing.
692     }
693
694     fn create_entry_fn(ccx: &CrateContext,
695                        sp: Span,
696                        rust_main: ValueRef,
697                        use_start_lang_item: bool) {
698         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
699
700         if declare::get_defined_value(ccx, "main").is_some() {
701             // FIXME: We should be smart and show a better diagnostic here.
702             ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
703                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
704                       .emit();
705             ccx.sess().abort_if_errors();
706             bug!();
707         }
708         let llfn = declare::declare_cfn(ccx, "main", llfty);
709
710         // `main` should respect same config for frame pointer elimination as rest of code
711         attributes::set_frame_pointer_elimination(ccx, llfn);
712
713         let bld = Builder::new_block(ccx, llfn, "top");
714
715         debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx, &bld);
716
717         let (start_fn, args) = if use_start_lang_item {
718             let start_def_id = ccx.tcx().require_lang_item(StartFnLangItem);
719             let start_instance = Instance::mono(ccx.tcx(), start_def_id);
720             let start_fn = callee::get_fn(ccx, start_instance);
721             (start_fn, vec![bld.pointercast(rust_main, Type::i8p(ccx).ptr_to()), get_param(llfn, 0),
722                 get_param(llfn, 1)])
723         } else {
724             debug!("using user-defined start fn");
725             (rust_main, vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)])
726         };
727
728         let result = bld.call(start_fn, &args, None);
729         bld.ret(result);
730     }
731 }
732
733 fn contains_null(s: &str) -> bool {
734     s.bytes().any(|b| b == 0)
735 }
736
737 fn write_metadata<'a, 'gcx>(tcx: TyCtxt<'a, 'gcx, 'gcx>,
738                             link_meta: &LinkMeta,
739                             exported_symbols: &NodeSet)
740                             -> (ContextRef, ModuleRef,
741                                 EncodedMetadata, EncodedMetadataHashes) {
742     use std::io::Write;
743     use flate2::Compression;
744     use flate2::write::DeflateEncoder;
745
746     let (metadata_llcx, metadata_llmod) = unsafe {
747         context::create_context_and_module(tcx.sess, "metadata")
748     };
749
750     #[derive(PartialEq, Eq, PartialOrd, Ord)]
751     enum MetadataKind {
752         None,
753         Uncompressed,
754         Compressed
755     }
756
757     let kind = tcx.sess.crate_types.borrow().iter().map(|ty| {
758         match *ty {
759             config::CrateTypeExecutable |
760             config::CrateTypeStaticlib |
761             config::CrateTypeCdylib => MetadataKind::None,
762
763             config::CrateTypeRlib => MetadataKind::Uncompressed,
764
765             config::CrateTypeDylib |
766             config::CrateTypeProcMacro => MetadataKind::Compressed,
767         }
768     }).max().unwrap();
769
770     if kind == MetadataKind::None {
771         return (metadata_llcx,
772                 metadata_llmod,
773                 EncodedMetadata::new(),
774                 EncodedMetadataHashes::new());
775     }
776
777     let cstore = &tcx.sess.cstore;
778     let (metadata, hashes) = cstore.encode_metadata(tcx,
779                                                     &link_meta,
780                                                     exported_symbols);
781     if kind == MetadataKind::Uncompressed {
782         return (metadata_llcx, metadata_llmod, metadata, hashes);
783     }
784
785     assert!(kind == MetadataKind::Compressed);
786     let mut compressed = cstore.metadata_encoding_version().to_vec();
787     DeflateEncoder::new(&mut compressed, Compression::Fast)
788         .write_all(&metadata.raw_data).unwrap();
789
790     let llmeta = C_bytes_in_context(metadata_llcx, &compressed);
791     let llconst = C_struct_in_context(metadata_llcx, &[llmeta], false);
792     let name = symbol_export::metadata_symbol_name(tcx);
793     let buf = CString::new(name).unwrap();
794     let llglobal = unsafe {
795         llvm::LLVMAddGlobal(metadata_llmod, val_ty(llconst).to_ref(), buf.as_ptr())
796     };
797     unsafe {
798         llvm::LLVMSetInitializer(llglobal, llconst);
799         let section_name = metadata::metadata_section_name(&tcx.sess.target.target);
800         let name = CString::new(section_name).unwrap();
801         llvm::LLVMSetSection(llglobal, name.as_ptr());
802
803         // Also generate a .section directive to force no
804         // flags, at least for ELF outputs, so that the
805         // metadata doesn't get loaded into memory.
806         let directive = format!(".section {}", section_name);
807         let directive = CString::new(directive).unwrap();
808         llvm::LLVMSetModuleInlineAsm(metadata_llmod, directive.as_ptr())
809     }
810     return (metadata_llcx, metadata_llmod, metadata, hashes);
811 }
812
813 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
814 // This is required to satisfy `dllimport` references to static data in .rlibs
815 // when using MSVC linker.  We do this only for data, as linker can fix up
816 // code references on its own.
817 // See #26591, #27438
818 fn create_imps(sess: &Session,
819                llvm_module: &ModuleLlvm) {
820     // The x86 ABI seems to require that leading underscores are added to symbol
821     // names, so we need an extra underscore on 32-bit. There's also a leading
822     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
823     // underscores added in front).
824     let prefix = if sess.target.target.target_pointer_width == "32" {
825         "\x01__imp__"
826     } else {
827         "\x01__imp_"
828     };
829     unsafe {
830         let exported: Vec<_> = iter_globals(llvm_module.llmod)
831                                    .filter(|&val| {
832                                        llvm::LLVMRustGetLinkage(val) ==
833                                        llvm::Linkage::ExternalLinkage &&
834                                        llvm::LLVMIsDeclaration(val) == 0
835                                    })
836                                    .collect();
837
838         let i8p_ty = Type::i8p_llcx(llvm_module.llcx);
839         for val in exported {
840             let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
841             let mut imp_name = prefix.as_bytes().to_vec();
842             imp_name.extend(name.to_bytes());
843             let imp_name = CString::new(imp_name).unwrap();
844             let imp = llvm::LLVMAddGlobal(llvm_module.llmod,
845                                           i8p_ty.to_ref(),
846                                           imp_name.as_ptr() as *const _);
847             let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
848             llvm::LLVMSetInitializer(imp, init);
849             llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
850         }
851     }
852 }
853
854 struct ValueIter {
855     cur: ValueRef,
856     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
857 }
858
859 impl Iterator for ValueIter {
860     type Item = ValueRef;
861
862     fn next(&mut self) -> Option<ValueRef> {
863         let old = self.cur;
864         if !old.is_null() {
865             self.cur = unsafe { (self.step)(old) };
866             Some(old)
867         } else {
868             None
869         }
870     }
871 }
872
873 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
874     unsafe {
875         ValueIter {
876             cur: llvm::LLVMGetFirstGlobal(llmod),
877             step: llvm::LLVMGetNextGlobal,
878         }
879     }
880 }
881
882 /// The context provided lists a set of reachable ids as calculated by
883 /// middle::reachable, but this contains far more ids and symbols than we're
884 /// actually exposing from the object file. This function will filter the set in
885 /// the context to the set of ids which correspond to symbols that are exposed
886 /// from the object file being generated.
887 ///
888 /// This list is later used by linkers to determine the set of symbols needed to
889 /// be exposed from a dynamic library and it's also encoded into the metadata.
890 pub fn find_exported_symbols(tcx: TyCtxt, reachable: &NodeSet) -> NodeSet {
891     reachable.iter().cloned().filter(|&id| {
892         // Next, we want to ignore some FFI functions that are not exposed from
893         // this crate. Reachable FFI functions can be lumped into two
894         // categories:
895         //
896         // 1. Those that are included statically via a static library
897         // 2. Those included otherwise (e.g. dynamically or via a framework)
898         //
899         // Although our LLVM module is not literally emitting code for the
900         // statically included symbols, it's an export of our library which
901         // needs to be passed on to the linker and encoded in the metadata.
902         //
903         // As a result, if this id is an FFI item (foreign item) then we only
904         // let it through if it's included statically.
905         match tcx.hir.get(id) {
906             hir_map::NodeForeignItem(..) => {
907                 let def_id = tcx.hir.local_def_id(id);
908                 tcx.sess.cstore.is_statically_included_foreign_item(def_id)
909             }
910
911             // Only consider nodes that actually have exported symbols.
912             hir_map::NodeItem(&hir::Item {
913                 node: hir::ItemStatic(..), .. }) |
914             hir_map::NodeItem(&hir::Item {
915                 node: hir::ItemFn(..), .. }) |
916             hir_map::NodeImplItem(&hir::ImplItem {
917                 node: hir::ImplItemKind::Method(..), .. }) => {
918                 let def_id = tcx.hir.local_def_id(id);
919                 let generics = tcx.generics_of(def_id);
920                 let attributes = tcx.get_attrs(def_id);
921                 (generics.parent_types == 0 && generics.types.is_empty()) &&
922                 // Functions marked with #[inline] are only ever translated
923                 // with "internal" linkage and are never exported.
924                 !attr::requests_inline(&attributes)
925             }
926
927             _ => false
928         }
929     }).collect()
930 }
931
932 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
933                              analysis: ty::CrateAnalysis,
934                              incremental_hashes_map: IncrementalHashesMap,
935                              output_filenames: &OutputFilenames)
936                              -> OngoingCrateTranslation {
937     check_for_rustc_errors_attr(tcx);
938
939     // Be careful with this krate: obviously it gives access to the
940     // entire contents of the krate. So if you push any subtasks of
941     // `TransCrate`, you need to be careful to register "reads" of the
942     // particular items that will be processed.
943     let krate = tcx.hir.krate();
944     let ty::CrateAnalysis { reachable, .. } = analysis;
945     let check_overflow = tcx.sess.overflow_checks();
946     let link_meta = link::build_link_meta(&incremental_hashes_map);
947     let exported_symbol_node_ids = find_exported_symbols(tcx, &reachable);
948
949     let shared_ccx = SharedCrateContext::new(tcx,
950                                              check_overflow,
951                                              output_filenames);
952     // Translate the metadata.
953     let (metadata_llcx, metadata_llmod, metadata, metadata_incr_hashes) =
954         time(tcx.sess.time_passes(), "write metadata", || {
955             write_metadata(tcx, &link_meta, &exported_symbol_node_ids)
956         });
957
958     let metadata_module = ModuleTranslation {
959         name: link::METADATA_MODULE_NAME.to_string(),
960         symbol_name_hash: 0, // we always rebuild metadata, at least for now
961         source: ModuleSource::Translated(ModuleLlvm {
962             llcx: metadata_llcx,
963             llmod: metadata_llmod,
964         }),
965         kind: ModuleKind::Metadata,
966     };
967
968     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
969     let time_graph = if tcx.sess.opts.debugging_opts.trans_time_graph {
970         Some(time_graph::TimeGraph::new())
971     } else {
972         None
973     };
974
975     // Skip crate items and just output metadata in -Z no-trans mode.
976     if tcx.sess.opts.debugging_opts.no_trans ||
977        !tcx.sess.opts.output_types.should_trans() {
978         let empty_exported_symbols = ExportedSymbols::empty();
979         let linker_info = LinkerInfo::new(&shared_ccx, &empty_exported_symbols);
980         let ongoing_translation = write::start_async_translation(
981             tcx.sess,
982             output_filenames,
983             time_graph.clone(),
984             tcx.crate_name(LOCAL_CRATE),
985             link_meta,
986             metadata,
987             Arc::new(empty_exported_symbols),
988             no_builtins,
989             None,
990             linker_info,
991             false);
992
993         ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, metadata_module, true);
994
995         assert_and_save_dep_graph(tcx,
996                                   incremental_hashes_map,
997                                   metadata_incr_hashes,
998                                   link_meta);
999
1000         ongoing_translation.check_for_errors(tcx.sess);
1001
1002         return ongoing_translation;
1003     }
1004
1005     let exported_symbols = Arc::new(ExportedSymbols::compute(tcx,
1006                                                              &exported_symbol_node_ids));
1007
1008     // Run the translation item collector and partition the collected items into
1009     // codegen units.
1010     let (translation_items, codegen_units) =
1011         collect_and_partition_translation_items(&shared_ccx, &exported_symbols);
1012
1013     assert!(codegen_units.len() <= 1 || !tcx.sess.lto());
1014
1015     let linker_info = LinkerInfo::new(&shared_ccx, &exported_symbols);
1016     let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1017                                                        "windows_subsystem");
1018     let windows_subsystem = subsystem.map(|subsystem| {
1019         if subsystem != "windows" && subsystem != "console" {
1020             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1021                                      `windows` and `console` are allowed",
1022                                     subsystem));
1023         }
1024         subsystem.to_string()
1025     });
1026
1027     let no_integrated_as = tcx.sess.opts.cg.no_integrated_as ||
1028         (tcx.sess.target.target.options.no_integrated_as &&
1029          (output_filenames.outputs.contains_key(&OutputType::Object) ||
1030           output_filenames.outputs.contains_key(&OutputType::Exe)));
1031
1032     let ongoing_translation = write::start_async_translation(
1033         tcx.sess,
1034         output_filenames,
1035         time_graph.clone(),
1036         tcx.crate_name(LOCAL_CRATE),
1037         link_meta,
1038         metadata,
1039         exported_symbols.clone(),
1040         no_builtins,
1041         windows_subsystem,
1042         linker_info,
1043         no_integrated_as);
1044
1045     // Translate an allocator shim, if any
1046     //
1047     // If LTO is enabled and we've got some previous LLVM module we translated
1048     // above, then we can just translate directly into that LLVM module. If not,
1049     // however, we need to create a separate module and trans into that. Note
1050     // that the separate translation is critical for the standard library where
1051     // the rlib's object file doesn't have allocator functions but the dylib
1052     // links in an object file that has allocator functions. When we're
1053     // compiling a final LTO artifact, though, there's no need to worry about
1054     // this as we're not working with this dual "rlib/dylib" functionality.
1055     let allocator_module = if tcx.sess.lto() {
1056         None
1057     } else if let Some(kind) = tcx.sess.allocator_kind.get() {
1058         unsafe {
1059             let (llcx, llmod) =
1060                 context::create_context_and_module(tcx.sess, "allocator");
1061             let modules = ModuleLlvm {
1062                 llmod: llmod,
1063                 llcx: llcx,
1064             };
1065             time(tcx.sess.time_passes(), "write allocator module", || {
1066                 allocator::trans(tcx, &modules, kind)
1067             });
1068
1069             Some(ModuleTranslation {
1070                 name: link::ALLOCATOR_MODULE_NAME.to_string(),
1071                 symbol_name_hash: 0, // we always rebuild allocator shims
1072                 source: ModuleSource::Translated(modules),
1073                 kind: ModuleKind::Allocator,
1074             })
1075         }
1076     } else {
1077         None
1078     };
1079
1080     if let Some(allocator_module) = allocator_module {
1081         ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess, allocator_module, false);
1082     }
1083
1084     let codegen_unit_count = codegen_units.len();
1085     ongoing_translation.submit_pre_translated_module_to_llvm(tcx.sess,
1086                                                              metadata_module,
1087                                                              codegen_unit_count == 0);
1088
1089     let translation_items = Arc::new(translation_items);
1090
1091     let mut all_stats = Stats::default();
1092     let mut module_dispositions = tcx.sess.opts.incremental.as_ref().map(|_| Vec::new());
1093
1094     // We sort the codegen units by size. This way we can schedule work for LLVM
1095     // a bit more efficiently. Note that "size" is defined rather crudely at the
1096     // moment as it is just the number of TransItems in the CGU, not taking into
1097     // account the size of each TransItem.
1098     let codegen_units = {
1099         let mut codegen_units = codegen_units;
1100         codegen_units.sort_by_key(|cgu| -(cgu.items().len() as isize));
1101         codegen_units
1102     };
1103
1104     let mut total_trans_time = Duration::new(0, 0);
1105
1106     for (cgu_index, cgu) in codegen_units.into_iter().enumerate() {
1107         ongoing_translation.wait_for_signal_to_translate_item();
1108         ongoing_translation.check_for_errors(tcx.sess);
1109
1110         let start_time = Instant::now();
1111
1112         let module = {
1113             let _timing_guard = time_graph
1114                 .as_ref()
1115                 .map(|time_graph| time_graph.start(write::TRANS_WORKER_TIMELINE,
1116                                                    write::TRANS_WORK_PACKAGE_KIND));
1117             let dep_node = cgu.work_product_dep_node();
1118             let ((stats, module), _) =
1119                 tcx.dep_graph.with_task(dep_node,
1120                                         AssertDepGraphSafe(&shared_ccx),
1121                                         AssertDepGraphSafe((cgu,
1122                                                             translation_items.clone(),
1123                                                             exported_symbols.clone())),
1124                                         module_translation);
1125             all_stats.extend(stats);
1126
1127             if let Some(ref mut module_dispositions) = module_dispositions {
1128                 module_dispositions.push(module.disposition());
1129             }
1130
1131             module
1132         };
1133
1134         let time_to_translate = Instant::now().duration_since(start_time);
1135
1136         // We assume that the cost to run LLVM on a CGU is proportional to
1137         // the time we needed for translating it.
1138         let cost = time_to_translate.as_secs() * 1_000_000_000 +
1139                    time_to_translate.subsec_nanos() as u64;
1140
1141         total_trans_time += time_to_translate;
1142
1143         let is_last_cgu = (cgu_index + 1) == codegen_unit_count;
1144
1145         ongoing_translation.submit_translated_module_to_llvm(tcx.sess,
1146                                                              module,
1147                                                              cost,
1148                                                              is_last_cgu);
1149         ongoing_translation.check_for_errors(tcx.sess);
1150     }
1151
1152     // Since the main thread is sometimes blocked during trans, we keep track
1153     // -Ztime-passes output manually.
1154     print_time_passes_entry(tcx.sess.time_passes(),
1155                             "translate to LLVM IR",
1156                             total_trans_time);
1157
1158     if let Some(module_dispositions) = module_dispositions {
1159         assert_module_sources::assert_module_sources(tcx, &module_dispositions);
1160     }
1161
1162     fn module_translation<'a, 'tcx>(
1163         scx: AssertDepGraphSafe<&SharedCrateContext<'a, 'tcx>>,
1164         args: AssertDepGraphSafe<(CodegenUnit<'tcx>,
1165                                   Arc<FxHashSet<TransItem<'tcx>>>,
1166                                   Arc<ExportedSymbols>)>)
1167         -> (Stats, ModuleTranslation)
1168     {
1169         // FIXME(#40304): We ought to be using the id as a key and some queries, I think.
1170         let AssertDepGraphSafe(scx) = scx;
1171         let AssertDepGraphSafe((cgu, crate_trans_items, exported_symbols)) = args;
1172
1173         let cgu_name = String::from(cgu.name());
1174         let cgu_id = cgu.work_product_id();
1175         let symbol_name_hash = cgu.compute_symbol_name_hash(scx, &exported_symbols);
1176
1177         // Check whether there is a previous work-product we can
1178         // re-use.  Not only must the file exist, and the inputs not
1179         // be dirty, but the hash of the symbols we will generate must
1180         // be the same.
1181         let previous_work_product =
1182             scx.dep_graph().previous_work_product(&cgu_id).and_then(|work_product| {
1183                 if work_product.input_hash == symbol_name_hash {
1184                     debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1185                     Some(work_product)
1186                 } else {
1187                     if scx.sess().opts.debugging_opts.incremental_info {
1188                         eprintln!("incremental: CGU `{}` invalidated because of \
1189                                    changed partitioning hash.",
1190                                    cgu.name());
1191                     }
1192                     debug!("trans_reuse_previous_work_products: \
1193                             not reusing {:?} because hash changed to {:?}",
1194                            work_product, symbol_name_hash);
1195                     None
1196                 }
1197             });
1198
1199         if let Some(buf) = previous_work_product {
1200             // Don't need to translate this module.
1201             let module = ModuleTranslation {
1202                 name: cgu_name,
1203                 symbol_name_hash,
1204                 source: ModuleSource::Preexisting(buf.clone()),
1205                 kind: ModuleKind::Regular,
1206             };
1207             return (Stats::default(), module);
1208         }
1209
1210         // Instantiate translation items without filling out definitions yet...
1211         let lcx = LocalCrateContext::new(scx, cgu, crate_trans_items, exported_symbols);
1212         let module = {
1213             let ccx = CrateContext::new(scx, &lcx);
1214             let trans_items = ccx.codegen_unit()
1215                                  .items_in_deterministic_order(ccx.tcx());
1216             for &(trans_item, (linkage, visibility)) in &trans_items {
1217                 trans_item.predefine(&ccx, linkage, visibility);
1218             }
1219
1220             // ... and now that we have everything pre-defined, fill out those definitions.
1221             for &(trans_item, _) in &trans_items {
1222                 trans_item.define(&ccx);
1223             }
1224
1225             // If this codegen unit contains the main function, also create the
1226             // wrapper here
1227             maybe_create_entry_wrapper(&ccx);
1228
1229             // Run replace-all-uses-with for statics that need it
1230             for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1231                 unsafe {
1232                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1233                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1234                     llvm::LLVMDeleteGlobal(old_g);
1235                 }
1236             }
1237
1238             // Create the llvm.used variable
1239             // This variable has type [N x i8*] and is stored in the llvm.metadata section
1240             if !ccx.used_statics().borrow().is_empty() {
1241                 let name = CString::new("llvm.used").unwrap();
1242                 let section = CString::new("llvm.metadata").unwrap();
1243                 let array = C_array(Type::i8(&ccx).ptr_to(), &*ccx.used_statics().borrow());
1244
1245                 unsafe {
1246                     let g = llvm::LLVMAddGlobal(ccx.llmod(),
1247                                                 val_ty(array).to_ref(),
1248                                                 name.as_ptr());
1249                     llvm::LLVMSetInitializer(g, array);
1250                     llvm::LLVMRustSetLinkage(g, llvm::Linkage::AppendingLinkage);
1251                     llvm::LLVMSetSection(g, section.as_ptr());
1252                 }
1253             }
1254
1255             // Finalize debuginfo
1256             if ccx.sess().opts.debuginfo != NoDebugInfo {
1257                 debuginfo::finalize(&ccx);
1258             }
1259
1260             let llvm_module = ModuleLlvm {
1261                 llcx: ccx.llcx(),
1262                 llmod: ccx.llmod(),
1263             };
1264
1265             // In LTO mode we inject the allocator shim into the existing
1266             // module.
1267             if ccx.sess().lto() {
1268                 if let Some(kind) = ccx.sess().allocator_kind.get() {
1269                     time(ccx.sess().time_passes(), "write allocator module", || {
1270                         unsafe {
1271                             allocator::trans(ccx.tcx(), &llvm_module, kind);
1272                         }
1273                     });
1274                 }
1275             }
1276
1277             // Adjust exported symbols for MSVC dllimport
1278             if ccx.sess().target.target.options.is_like_msvc &&
1279                ccx.sess().crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1280                 create_imps(ccx.sess(), &llvm_module);
1281             }
1282
1283             ModuleTranslation {
1284                 name: cgu_name,
1285                 symbol_name_hash,
1286                 source: ModuleSource::Translated(llvm_module),
1287                 kind: ModuleKind::Regular,
1288             }
1289         };
1290
1291         (lcx.into_stats(), module)
1292     }
1293
1294     symbol_names_test::report_symbol_names(tcx);
1295
1296     if shared_ccx.sess().trans_stats() {
1297         println!("--- trans stats ---");
1298         println!("n_glues_created: {}", all_stats.n_glues_created.get());
1299         println!("n_null_glues: {}", all_stats.n_null_glues.get());
1300         println!("n_real_glues: {}", all_stats.n_real_glues.get());
1301
1302         println!("n_fns: {}", all_stats.n_fns.get());
1303         println!("n_inlines: {}", all_stats.n_inlines.get());
1304         println!("n_closures: {}", all_stats.n_closures.get());
1305         println!("fn stats:");
1306         all_stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1307             insns_b.cmp(&insns_a)
1308         });
1309         for tuple in all_stats.fn_stats.borrow().iter() {
1310             match *tuple {
1311                 (ref name, insns) => {
1312                     println!("{} insns, {}", insns, *name);
1313                 }
1314             }
1315         }
1316     }
1317
1318     if shared_ccx.sess().count_llvm_insns() {
1319         for (k, v) in all_stats.llvm_insns.borrow().iter() {
1320             println!("{:7} {}", *v, *k);
1321         }
1322     }
1323
1324     ongoing_translation.check_for_errors(tcx.sess);
1325
1326     assert_and_save_dep_graph(tcx,
1327                               incremental_hashes_map,
1328                               metadata_incr_hashes,
1329                               link_meta);
1330     ongoing_translation
1331 }
1332
1333 fn assert_and_save_dep_graph<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1334                                        incremental_hashes_map: IncrementalHashesMap,
1335                                        metadata_incr_hashes: EncodedMetadataHashes,
1336                                        link_meta: LinkMeta) {
1337     time(tcx.sess.time_passes(),
1338          "assert dep graph",
1339          || rustc_incremental::assert_dep_graph(tcx));
1340
1341     time(tcx.sess.time_passes(),
1342          "serialize dep graph",
1343          || rustc_incremental::save_dep_graph(tcx,
1344                                               incremental_hashes_map,
1345                                               &metadata_incr_hashes,
1346                                               link_meta.crate_hash));
1347 }
1348
1349 #[inline(never)] // give this a place in the profiler
1350 fn assert_symbols_are_distinct<'a, 'tcx, I>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trans_items: I)
1351     where I: Iterator<Item=&'a TransItem<'tcx>>
1352 {
1353     let mut symbols: Vec<_> = trans_items.map(|trans_item| {
1354         (trans_item, trans_item.symbol_name(tcx))
1355     }).collect();
1356
1357     (&mut symbols[..]).sort_by(|&(_, ref sym1), &(_, ref sym2)|{
1358         sym1.cmp(sym2)
1359     });
1360
1361     for pair in (&symbols[..]).windows(2) {
1362         let sym1 = &pair[0].1;
1363         let sym2 = &pair[1].1;
1364
1365         if *sym1 == *sym2 {
1366             let trans_item1 = pair[0].0;
1367             let trans_item2 = pair[1].0;
1368
1369             let span1 = trans_item1.local_span(tcx);
1370             let span2 = trans_item2.local_span(tcx);
1371
1372             // Deterministically select one of the spans for error reporting
1373             let span = match (span1, span2) {
1374                 (Some(span1), Some(span2)) => {
1375                     Some(if span1.lo.0 > span2.lo.0 {
1376                         span1
1377                     } else {
1378                         span2
1379                     })
1380                 }
1381                 (Some(span), None) |
1382                 (None, Some(span)) => Some(span),
1383                 _ => None
1384             };
1385
1386             let error_message = format!("symbol `{}` is already defined", sym1);
1387
1388             if let Some(span) = span {
1389                 tcx.sess.span_fatal(span, &error_message)
1390             } else {
1391                 tcx.sess.fatal(&error_message)
1392             }
1393         }
1394     }
1395 }
1396
1397 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
1398                                                      exported_symbols: &ExportedSymbols)
1399                                                      -> (FxHashSet<TransItem<'tcx>>,
1400                                                          Vec<CodegenUnit<'tcx>>) {
1401     let time_passes = scx.sess().time_passes();
1402
1403     let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1404         Some(ref s) => {
1405             let mode_string = s.to_lowercase();
1406             let mode_string = mode_string.trim();
1407             if mode_string == "eager" {
1408                 TransItemCollectionMode::Eager
1409             } else {
1410                 if mode_string != "lazy" {
1411                     let message = format!("Unknown codegen-item collection mode '{}'. \
1412                                            Falling back to 'lazy' mode.",
1413                                            mode_string);
1414                     scx.sess().warn(&message);
1415                 }
1416
1417                 TransItemCollectionMode::Lazy
1418             }
1419         }
1420         None => TransItemCollectionMode::Lazy
1421     };
1422
1423     let (items, inlining_map) =
1424         time(time_passes, "translation item collection", || {
1425             collector::collect_crate_translation_items(&scx,
1426                                                        exported_symbols,
1427                                                        collection_mode)
1428     });
1429
1430     assert_symbols_are_distinct(scx.tcx(), items.iter());
1431
1432     let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1433         PartitioningStrategy::PerModule
1434     } else {
1435         PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1436     };
1437
1438     let codegen_units = time(time_passes, "codegen unit partitioning", || {
1439         partitioning::partition(scx,
1440                                 items.iter().cloned(),
1441                                 strategy,
1442                                 &inlining_map,
1443                                 exported_symbols)
1444     });
1445
1446     assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1447             scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1448
1449     let translation_items: FxHashSet<TransItem<'tcx>> = items.iter().cloned().collect();
1450
1451     if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1452         let mut item_to_cgus = FxHashMap();
1453
1454         for cgu in &codegen_units {
1455             for (&trans_item, &linkage) in cgu.items() {
1456                 item_to_cgus.entry(trans_item)
1457                             .or_insert(Vec::new())
1458                             .push((cgu.name().clone(), linkage));
1459             }
1460         }
1461
1462         let mut item_keys: Vec<_> = items
1463             .iter()
1464             .map(|i| {
1465                 let mut output = i.to_string(scx.tcx());
1466                 output.push_str(" @@");
1467                 let mut empty = Vec::new();
1468                 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1469                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1470                 cgus.dedup();
1471                 for &(ref cgu_name, (linkage, _)) in cgus.iter() {
1472                     output.push_str(" ");
1473                     output.push_str(&cgu_name);
1474
1475                     let linkage_abbrev = match linkage {
1476                         llvm::Linkage::ExternalLinkage => "External",
1477                         llvm::Linkage::AvailableExternallyLinkage => "Available",
1478                         llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1479                         llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1480                         llvm::Linkage::WeakAnyLinkage => "WeakAny",
1481                         llvm::Linkage::WeakODRLinkage => "WeakODR",
1482                         llvm::Linkage::AppendingLinkage => "Appending",
1483                         llvm::Linkage::InternalLinkage => "Internal",
1484                         llvm::Linkage::PrivateLinkage => "Private",
1485                         llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1486                         llvm::Linkage::CommonLinkage => "Common",
1487                     };
1488
1489                     output.push_str("[");
1490                     output.push_str(linkage_abbrev);
1491                     output.push_str("]");
1492                 }
1493                 output
1494             })
1495             .collect();
1496
1497         item_keys.sort();
1498
1499         for item in item_keys {
1500             println!("TRANS_ITEM {}", item);
1501         }
1502     }
1503
1504     (translation_items, codegen_units)
1505 }