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