]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/base.rs
Add --crate-type metadata
[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 #![allow(non_camel_case_types)]
27
28 use super::CrateTranslation;
29 use super::ModuleLlvm;
30 use super::ModuleSource;
31 use super::ModuleTranslation;
32
33 use assert_module_sources;
34 use back::link;
35 use back::linker::LinkerInfo;
36 use llvm::{Linkage, ValueRef, Vector, get_param};
37 use llvm;
38 use rustc::hir::def::Def;
39 use rustc::hir::def_id::DefId;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use rustc::ty::subst::Substs;
42 use rustc::traits;
43 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
44 use rustc::ty::adjustment::CustomCoerceUnsized;
45 use rustc::dep_graph::{DepNode, WorkProduct};
46 use rustc::hir::map as hir_map;
47 use rustc::util::common::time;
48 use session::config::{self, NoDebugInfo, OutputType};
49 use rustc_incremental::IncrementalHashesMap;
50 use session::Session;
51 use abi::{self, Abi, FnType};
52 use adt;
53 use attributes;
54 use build::*;
55 use builder::{Builder, noname};
56 use callee::{Callee};
57 use common::{Block, C_bool, C_bytes_in_context, C_i32, C_uint};
58 use collector::{self, TransItemCollectionMode};
59 use common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
60 use common::{CrateContext, FunctionContext};
61 use common::{Result};
62 use common::{fulfill_obligation};
63 use common::{type_is_zero_size, val_ty};
64 use common;
65 use consts;
66 use context::{SharedCrateContext, CrateContextList};
67 use debuginfo::{self, DebugLoc};
68 use declare;
69 use machine;
70 use machine::{llalign_of_min, llsize_of};
71 use meth;
72 use mir;
73 use monomorphize::{self, Instance};
74 use partitioning::{self, PartitioningStrategy, CodegenUnit};
75 use symbol_map::SymbolMap;
76 use symbol_names_test;
77 use trans_item::{TransItem, DefPathBasedNames};
78 use type_::Type;
79 use type_of;
80 use value::Value;
81 use Disr;
82 use util::nodemap::{NodeSet, FxHashMap, FxHashSet};
83
84 use arena::TypedArena;
85 use libc::c_uint;
86 use std::ffi::{CStr, CString};
87 use std::borrow::Cow;
88 use std::cell::{Cell, RefCell};
89 use std::ptr;
90 use std::rc::Rc;
91 use std::str;
92 use std::i32;
93 use syntax_pos::{Span, DUMMY_SP};
94 use syntax::attr;
95 use rustc::hir;
96 use syntax::ast;
97
98 thread_local! {
99     static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
100         RefCell::new(None)
101     }
102 }
103
104 pub fn with_insn_ctxt<F>(blk: F)
105     where F: FnOnce(&[&'static str])
106 {
107     TASK_LOCAL_INSN_KEY.with(move |slot| {
108         slot.borrow().as_ref().map(move |s| blk(s));
109     })
110 }
111
112 pub fn init_insn_ctxt() {
113     TASK_LOCAL_INSN_KEY.with(|slot| {
114         *slot.borrow_mut() = Some(Vec::new());
115     });
116 }
117
118 pub struct _InsnCtxt {
119     _cannot_construct_outside_of_this_module: (),
120 }
121
122 impl Drop for _InsnCtxt {
123     fn drop(&mut self) {
124         TASK_LOCAL_INSN_KEY.with(|slot| {
125             if let Some(ctx) = slot.borrow_mut().as_mut() {
126                 ctx.pop();
127             }
128         })
129     }
130 }
131
132 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
133     debug!("new InsnCtxt: {}", s);
134     TASK_LOCAL_INSN_KEY.with(|slot| {
135         if let Some(ctx) = slot.borrow_mut().as_mut() {
136             ctx.push(s)
137         }
138     });
139     _InsnCtxt {
140         _cannot_construct_outside_of_this_module: (),
141     }
142 }
143
144 pub struct StatRecorder<'a, 'tcx: 'a> {
145     ccx: &'a CrateContext<'a, 'tcx>,
146     name: Option<String>,
147     istart: usize,
148 }
149
150 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
151     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
152         let istart = ccx.stats().n_llvm_insns.get();
153         StatRecorder {
154             ccx: ccx,
155             name: Some(name),
156             istart: istart,
157         }
158     }
159 }
160
161 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
162     fn drop(&mut self) {
163         if self.ccx.sess().trans_stats() {
164             let iend = self.ccx.stats().n_llvm_insns.get();
165             self.ccx
166                 .stats()
167                 .fn_stats
168                 .borrow_mut()
169                 .push((self.name.take().unwrap(), iend - self.istart));
170             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
171             // Reset LLVM insn count to avoid compound costs.
172             self.ccx.stats().n_llvm_insns.set(self.istart);
173         }
174     }
175 }
176
177 pub fn get_meta(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
178     StructGEP(bcx, fat_ptr, abi::FAT_PTR_EXTRA)
179 }
180
181 pub fn get_dataptr(bcx: Block, fat_ptr: ValueRef) -> ValueRef {
182     StructGEP(bcx, fat_ptr, abi::FAT_PTR_ADDR)
183 }
184
185 pub fn get_meta_builder(b: &Builder, fat_ptr: ValueRef) -> ValueRef {
186     b.struct_gep(fat_ptr, abi::FAT_PTR_EXTRA)
187 }
188
189 pub fn get_dataptr_builder(b: &Builder, fat_ptr: ValueRef) -> ValueRef {
190     b.struct_gep(fat_ptr, abi::FAT_PTR_ADDR)
191 }
192
193 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, info_ty: Ty<'tcx>, it: LangItem) -> DefId {
194     match bcx.tcx().lang_items.require(it) {
195         Ok(id) => id,
196         Err(s) => {
197             bcx.sess().fatal(&format!("allocation of `{}` {}", info_ty, s));
198         }
199     }
200 }
201
202 // The following malloc_raw_dyn* functions allocate a box to contain
203 // a given type, but with a potentially dynamic size.
204
205 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
206                                   llty_ptr: Type,
207                                   info_ty: Ty<'tcx>,
208                                   size: ValueRef,
209                                   align: ValueRef,
210                                   debug_loc: DebugLoc)
211                                   -> Result<'blk, 'tcx> {
212     let _icx = push_ctxt("malloc_raw_exchange");
213
214     // Allocate space:
215     let def_id = require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem);
216     let r = Callee::def(bcx.ccx(), def_id, bcx.tcx().intern_substs(&[]))
217         .call(bcx, debug_loc, &[size, align], None);
218
219     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
220 }
221
222
223 pub fn bin_op_to_icmp_predicate(op: hir::BinOp_,
224                                 signed: bool)
225                                 -> llvm::IntPredicate {
226     match op {
227         hir::BiEq => llvm::IntEQ,
228         hir::BiNe => llvm::IntNE,
229         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
230         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
231         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
232         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
233         op => {
234             bug!("comparison_op_to_icmp_predicate: expected comparison operator, \
235                   found {:?}",
236                  op)
237         }
238     }
239 }
240
241 pub fn bin_op_to_fcmp_predicate(op: hir::BinOp_) -> llvm::RealPredicate {
242     match op {
243         hir::BiEq => llvm::RealOEQ,
244         hir::BiNe => llvm::RealUNE,
245         hir::BiLt => llvm::RealOLT,
246         hir::BiLe => llvm::RealOLE,
247         hir::BiGt => llvm::RealOGT,
248         hir::BiGe => llvm::RealOGE,
249         op => {
250             bug!("comparison_op_to_fcmp_predicate: expected comparison operator, \
251                   found {:?}",
252                  op);
253         }
254     }
255 }
256
257 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
258                                       lhs: ValueRef,
259                                       rhs: ValueRef,
260                                       t: Ty<'tcx>,
261                                       ret_ty: Type,
262                                       op: hir::BinOp_,
263                                       debug_loc: DebugLoc)
264                                       -> ValueRef {
265     let signed = match t.sty {
266         ty::TyFloat(_) => {
267             let cmp = bin_op_to_fcmp_predicate(op);
268             return SExt(bcx, FCmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty);
269         },
270         ty::TyUint(_) => false,
271         ty::TyInt(_) => true,
272         _ => bug!("compare_simd_types: invalid SIMD type"),
273     };
274
275     let cmp = bin_op_to_icmp_predicate(op, signed);
276     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
277     // to get the correctly sized type. This will compile to a single instruction
278     // once the IR is converted to assembly if the SIMD instruction is supported
279     // by the target architecture.
280     SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty)
281 }
282
283 /// Retrieve the information we are losing (making dynamic) in an unsizing
284 /// adjustment.
285 ///
286 /// The `old_info` argument is a bit funny. It is intended for use
287 /// in an upcast, where the new vtable for an object will be drived
288 /// from the old one.
289 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
290                                 source: Ty<'tcx>,
291                                 target: Ty<'tcx>,
292                                 old_info: Option<ValueRef>)
293                                 -> ValueRef {
294     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
295     match (&source.sty, &target.sty) {
296         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
297         (&ty::TyTrait(_), &ty::TyTrait(_)) => {
298             // For now, upcasts are limited to changes in marker
299             // traits, and hence never actually require an actual
300             // change to the vtable.
301             old_info.expect("unsized_info: missing old info for trait upcast")
302         }
303         (_, &ty::TyTrait(ref data)) => {
304             let trait_ref = data.principal.with_self_ty(ccx.tcx(), source);
305             let trait_ref = ccx.tcx().erase_regions(&trait_ref);
306             consts::ptrcast(meth::get_vtable(ccx, trait_ref),
307                             Type::vtable_ptr(ccx))
308         }
309         _ => bug!("unsized_info: invalid unsizing {:?} -> {:?}",
310                                      source,
311                                      target),
312     }
313 }
314
315 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
316 pub fn unsize_thin_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
317                                    src: ValueRef,
318                                    src_ty: Ty<'tcx>,
319                                    dst_ty: Ty<'tcx>)
320                                    -> (ValueRef, ValueRef) {
321     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
322     match (&src_ty.sty, &dst_ty.sty) {
323         (&ty::TyBox(a), &ty::TyBox(b)) |
324         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
325          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
326         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
327          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
328         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
329          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
330             assert!(common::type_is_sized(bcx.tcx(), a));
331             let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), b).ptr_to();
332             (PointerCast(bcx, src, ptr_ty),
333              unsized_info(bcx.ccx(), a, b, None))
334         }
335         _ => bug!("unsize_thin_ptr: called on bad types"),
336     }
337 }
338
339 /// Coerce `src`, which is a reference to a value of type `src_ty`,
340 /// to a value of type `dst_ty` and store the result in `dst`
341 pub fn coerce_unsized_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
342                                        src: ValueRef,
343                                        src_ty: Ty<'tcx>,
344                                        dst: ValueRef,
345                                        dst_ty: Ty<'tcx>) {
346     match (&src_ty.sty, &dst_ty.sty) {
347         (&ty::TyBox(..), &ty::TyBox(..)) |
348         (&ty::TyRef(..), &ty::TyRef(..)) |
349         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
350         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
351             let (base, info) = if common::type_is_fat_ptr(bcx.tcx(), src_ty) {
352                 // fat-ptr to fat-ptr unsize preserves the vtable
353                 // i.e. &'a fmt::Debug+Send => &'a fmt::Debug
354                 // So we need to pointercast the base to ensure
355                 // the types match up.
356                 let (base, info) = load_fat_ptr(bcx, src, src_ty);
357                 let llcast_ty = type_of::fat_ptr_base_ty(bcx.ccx(), dst_ty);
358                 let base = PointerCast(bcx, base, llcast_ty);
359                 (base, info)
360             } else {
361                 let base = load_ty(bcx, src, src_ty);
362                 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
363             };
364             store_fat_ptr(bcx, base, info, dst, dst_ty);
365         }
366
367         (&ty::TyAdt(def_a, substs_a), &ty::TyAdt(def_b, substs_b)) => {
368             assert_eq!(def_a, def_b);
369
370             let src_fields = def_a.variants[0].fields.iter().map(|f| {
371                 monomorphize::field_ty(bcx.tcx(), substs_a, f)
372             });
373             let dst_fields = def_b.variants[0].fields.iter().map(|f| {
374                 monomorphize::field_ty(bcx.tcx(), substs_b, f)
375             });
376
377             let src = adt::MaybeSizedValue::sized(src);
378             let dst = adt::MaybeSizedValue::sized(dst);
379
380             let iter = src_fields.zip(dst_fields).enumerate();
381             for (i, (src_fty, dst_fty)) in iter {
382                 if type_is_zero_size(bcx.ccx(), dst_fty) {
383                     continue;
384                 }
385
386                 let src_f = adt::trans_field_ptr(bcx, src_ty, src, Disr(0), i);
387                 let dst_f = adt::trans_field_ptr(bcx, dst_ty, dst, Disr(0), i);
388                 if src_fty == dst_fty {
389                     memcpy_ty(bcx, dst_f, src_f, src_fty);
390                 } else {
391                     coerce_unsized_into(bcx, src_f, src_fty, dst_f, dst_fty);
392                 }
393             }
394         }
395         _ => bug!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
396                   src_ty,
397                   dst_ty),
398     }
399 }
400
401 pub fn custom_coerce_unsize_info<'scx, 'tcx>(scx: &SharedCrateContext<'scx, 'tcx>,
402                                              source_ty: Ty<'tcx>,
403                                              target_ty: Ty<'tcx>)
404                                              -> CustomCoerceUnsized {
405     let trait_ref = ty::Binder(ty::TraitRef {
406         def_id: scx.tcx().lang_items.coerce_unsized_trait().unwrap(),
407         substs: scx.tcx().mk_substs_trait(source_ty, &[target_ty])
408     });
409
410     match fulfill_obligation(scx, DUMMY_SP, trait_ref) {
411         traits::VtableImpl(traits::VtableImplData { impl_def_id, .. }) => {
412             scx.tcx().custom_coerce_unsized_kind(impl_def_id)
413         }
414         vtable => {
415             bug!("invalid CoerceUnsized vtable: {:?}", vtable);
416         }
417     }
418 }
419
420 pub fn cast_shift_expr_rhs(cx: Block, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
421     cast_shift_rhs(op, lhs, rhs, |a, b| Trunc(cx, a, b), |a, b| ZExt(cx, a, b))
422 }
423
424 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
425     cast_shift_rhs(op,
426                    lhs,
427                    rhs,
428                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
429                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
430 }
431
432 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
433                         lhs: ValueRef,
434                         rhs: ValueRef,
435                         trunc: F,
436                         zext: G)
437                         -> ValueRef
438     where F: FnOnce(ValueRef, Type) -> ValueRef,
439           G: FnOnce(ValueRef, Type) -> ValueRef
440 {
441     // Shifts may have any size int on the rhs
442     if op.is_shift() {
443         let mut rhs_llty = val_ty(rhs);
444         let mut lhs_llty = val_ty(lhs);
445         if rhs_llty.kind() == Vector {
446             rhs_llty = rhs_llty.element_type()
447         }
448         if lhs_llty.kind() == Vector {
449             lhs_llty = lhs_llty.element_type()
450         }
451         let rhs_sz = rhs_llty.int_width();
452         let lhs_sz = lhs_llty.int_width();
453         if lhs_sz < rhs_sz {
454             trunc(rhs, lhs_llty)
455         } else if lhs_sz > rhs_sz {
456             // FIXME (#1877: If shifting by negative
457             // values becomes not undefined then this is wrong.
458             zext(rhs, lhs_llty)
459         } else {
460             rhs
461         }
462     } else {
463         rhs
464     }
465 }
466
467 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
468                           llfn: ValueRef,
469                           llargs: &[ValueRef],
470                           debug_loc: DebugLoc)
471                           -> (ValueRef, Block<'blk, 'tcx>) {
472     let _icx = push_ctxt("invoke_");
473     if bcx.unreachable.get() {
474         return (C_null(Type::i8(bcx.ccx())), bcx);
475     }
476
477     if need_invoke(bcx) {
478         debug!("invoking {:?} at {:?}", Value(llfn), bcx.llbb);
479         for &llarg in llargs {
480             debug!("arg: {:?}", Value(llarg));
481         }
482         let normal_bcx = bcx.fcx.new_block("normal-return");
483         let landing_pad = bcx.fcx.get_landing_pad();
484
485         let llresult = Invoke(bcx,
486                               llfn,
487                               &llargs[..],
488                               normal_bcx.llbb,
489                               landing_pad,
490                               debug_loc);
491         return (llresult, normal_bcx);
492     } else {
493         debug!("calling {:?} at {:?}", Value(llfn), bcx.llbb);
494         for &llarg in llargs {
495             debug!("arg: {:?}", Value(llarg));
496         }
497
498         let llresult = Call(bcx, llfn, &llargs[..], debug_loc);
499         return (llresult, bcx);
500     }
501 }
502
503 /// Returns whether this session's target will use SEH-based unwinding.
504 ///
505 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
506 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
507 /// 64-bit MinGW) instead of "full SEH".
508 pub fn wants_msvc_seh(sess: &Session) -> bool {
509     sess.target.target.options.is_like_msvc
510 }
511
512 pub fn avoid_invoke(bcx: Block) -> bool {
513     bcx.sess().no_landing_pads() || bcx.lpad().is_some()
514 }
515
516 pub fn need_invoke(bcx: Block) -> bool {
517     if avoid_invoke(bcx) {
518         false
519     } else {
520         bcx.fcx.needs_invoke()
521     }
522 }
523
524 pub fn call_assume<'a, 'tcx>(b: &Builder<'a, 'tcx>, val: ValueRef) {
525     let assume_intrinsic = b.ccx.get_intrinsic("llvm.assume");
526     b.call(assume_intrinsic, &[val], None);
527 }
528
529 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
530 /// differs from the type used for SSA values. Also handles various special cases where the type
531 /// gives us better information about what we are loading.
532 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
533     if cx.unreachable.get() {
534         return C_undef(type_of::type_of(cx.ccx(), t));
535     }
536     load_ty_builder(&B(cx), ptr, t)
537 }
538
539 pub fn load_ty_builder<'a, 'tcx>(b: &Builder<'a, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
540     let ccx = b.ccx;
541     if type_is_zero_size(ccx, t) {
542         return C_undef(type_of::type_of(ccx, t));
543     }
544
545     unsafe {
546         let global = llvm::LLVMIsAGlobalVariable(ptr);
547         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
548             let val = llvm::LLVMGetInitializer(global);
549             if !val.is_null() {
550                 if t.is_bool() {
551                     return llvm::LLVMConstTrunc(val, Type::i1(ccx).to_ref());
552                 }
553                 return val;
554             }
555         }
556     }
557
558     if t.is_bool() {
559         b.trunc(b.load_range_assert(ptr, 0, 2, llvm::False), Type::i1(ccx))
560     } else if t.is_char() {
561         // a char is a Unicode codepoint, and so takes values from 0
562         // to 0x10FFFF inclusive only.
563         b.load_range_assert(ptr, 0, 0x10FFFF + 1, llvm::False)
564     } else if (t.is_region_ptr() || t.is_unique()) &&
565               !common::type_is_fat_ptr(ccx.tcx(), t) {
566         b.load_nonnull(ptr)
567     } else {
568         b.load(ptr)
569     }
570 }
571
572 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
573 /// differs from the type used for SSA values.
574 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
575     if cx.unreachable.get() {
576         return;
577     }
578
579     debug!("store_ty: {:?} : {:?} <- {:?}", Value(dst), t, Value(v));
580
581     if common::type_is_fat_ptr(cx.tcx(), t) {
582         let lladdr = ExtractValue(cx, v, abi::FAT_PTR_ADDR);
583         let llextra = ExtractValue(cx, v, abi::FAT_PTR_EXTRA);
584         store_fat_ptr(cx, lladdr, llextra, dst, t);
585     } else {
586         Store(cx, from_immediate(cx, v), dst);
587     }
588 }
589
590 pub fn store_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
591                                  data: ValueRef,
592                                  extra: ValueRef,
593                                  dst: ValueRef,
594                                  _ty: Ty<'tcx>) {
595     // FIXME: emit metadata
596     Store(cx, data, get_dataptr(cx, dst));
597     Store(cx, extra, get_meta(cx, dst));
598 }
599
600 pub fn load_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
601                                 src: ValueRef,
602                                 ty: Ty<'tcx>)
603                                 -> (ValueRef, ValueRef)
604 {
605     if cx.unreachable.get() {
606         // FIXME: remove me
607         return (Load(cx, get_dataptr(cx, src)),
608                 Load(cx, get_meta(cx, src)));
609     }
610
611     load_fat_ptr_builder(&B(cx), src, ty)
612 }
613
614 pub fn load_fat_ptr_builder<'a, 'tcx>(
615     b: &Builder<'a, 'tcx>,
616     src: ValueRef,
617     t: Ty<'tcx>)
618     -> (ValueRef, ValueRef)
619 {
620
621     let ptr = get_dataptr_builder(b, src);
622     let ptr = if t.is_region_ptr() || t.is_unique() {
623         b.load_nonnull(ptr)
624     } else {
625         b.load(ptr)
626     };
627
628     // FIXME: emit metadata on `meta`.
629     let meta = b.load(get_meta_builder(b, src));
630
631     (ptr, meta)
632 }
633
634 pub fn from_immediate(bcx: Block, val: ValueRef) -> ValueRef {
635     if val_ty(val) == Type::i1(bcx.ccx()) {
636         ZExt(bcx, val, Type::i8(bcx.ccx()))
637     } else {
638         val
639     }
640 }
641
642 pub fn to_immediate(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
643     if ty.is_bool() {
644         Trunc(bcx, val, Type::i1(bcx.ccx()))
645     } else {
646         val
647     }
648 }
649
650 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, val: ValueRef, f: F) -> Block<'blk, 'tcx>
651     where F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>
652 {
653     let _icx = push_ctxt("with_cond");
654
655     if bcx.unreachable.get() || common::const_to_opt_uint(val) == Some(0) {
656         return bcx;
657     }
658
659     let fcx = bcx.fcx;
660     let next_cx = fcx.new_block("next");
661     let cond_cx = fcx.new_block("cond");
662     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
663     let after_cx = f(cond_cx);
664     if !after_cx.terminated.get() {
665         Br(after_cx, next_cx.llbb, DebugLoc::None);
666     }
667     next_cx
668 }
669
670 pub enum Lifetime { Start, End }
671
672 // If LLVM lifetime intrinsic support is enabled (i.e. optimizations
673 // on), and `ptr` is nonzero-sized, then extracts the size of `ptr`
674 // and the intrinsic for `lt` and passes them to `emit`, which is in
675 // charge of generating code to call the passed intrinsic on whatever
676 // block of generated code is targetted for the intrinsic.
677 //
678 // If LLVM lifetime intrinsic support is disabled (i.e.  optimizations
679 // off) or `ptr` is zero-sized, then no-op (does not call `emit`).
680 fn core_lifetime_emit<'blk, 'tcx, F>(ccx: &'blk CrateContext<'blk, 'tcx>,
681                                      ptr: ValueRef,
682                                      lt: Lifetime,
683                                      emit: F)
684     where F: FnOnce(&'blk CrateContext<'blk, 'tcx>, machine::llsize, ValueRef)
685 {
686     if ccx.sess().opts.optimize == config::OptLevel::No {
687         return;
688     }
689
690     let _icx = push_ctxt(match lt {
691         Lifetime::Start => "lifetime_start",
692         Lifetime::End => "lifetime_end"
693     });
694
695     let size = machine::llsize_of_alloc(ccx, val_ty(ptr).element_type());
696     if size == 0 {
697         return;
698     }
699
700     let lifetime_intrinsic = ccx.get_intrinsic(match lt {
701         Lifetime::Start => "llvm.lifetime.start",
702         Lifetime::End => "llvm.lifetime.end"
703     });
704     emit(ccx, size, lifetime_intrinsic)
705 }
706
707 impl Lifetime {
708     pub fn call(self, b: &Builder, ptr: ValueRef) {
709         core_lifetime_emit(b.ccx, ptr, self, |ccx, size, lifetime_intrinsic| {
710             let ptr = b.pointercast(ptr, Type::i8p(ccx));
711             b.call(lifetime_intrinsic, &[C_u64(ccx, size), ptr], None);
712         });
713     }
714 }
715
716 pub fn call_lifetime_start(bcx: Block, ptr: ValueRef) {
717     if !bcx.unreachable.get() {
718         Lifetime::Start.call(&bcx.build(), ptr);
719     }
720 }
721
722 pub fn call_lifetime_end(bcx: Block, ptr: ValueRef) {
723     if !bcx.unreachable.get() {
724         Lifetime::End.call(&bcx.build(), ptr);
725     }
726 }
727
728 // Generates code for resumption of unwind at the end of a landing pad.
729 pub fn trans_unwind_resume(bcx: Block, lpval: ValueRef) {
730     if !bcx.sess().target.target.options.custom_unwind_resume {
731         Resume(bcx, lpval);
732     } else {
733         let exc_ptr = ExtractValue(bcx, lpval, 0);
734         bcx.fcx.eh_unwind_resume()
735             .call(bcx, DebugLoc::None, &[exc_ptr], None);
736     }
737 }
738
739 pub fn call_memcpy<'bcx, 'tcx>(b: &Builder<'bcx, 'tcx>,
740                                dst: ValueRef,
741                                src: ValueRef,
742                                n_bytes: ValueRef,
743                                align: u32) {
744     let _icx = push_ctxt("call_memcpy");
745     let ccx = b.ccx;
746     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
747     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
748     let memcpy = ccx.get_intrinsic(&key);
749     let src_ptr = b.pointercast(src, Type::i8p(ccx));
750     let dst_ptr = b.pointercast(dst, Type::i8p(ccx));
751     let size = b.intcast(n_bytes, ccx.int_type());
752     let align = C_i32(ccx, align as i32);
753     let volatile = C_bool(ccx, false);
754     b.call(memcpy, &[dst_ptr, src_ptr, size, align, volatile], None);
755 }
756
757 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, dst: ValueRef, src: ValueRef, t: Ty<'tcx>) {
758     let _icx = push_ctxt("memcpy_ty");
759     let ccx = bcx.ccx();
760
761     if type_is_zero_size(ccx, t) || bcx.unreachable.get() {
762         return;
763     }
764
765     if t.is_structural() {
766         let llty = type_of::type_of(ccx, t);
767         let llsz = llsize_of(ccx, llty);
768         let llalign = type_of::align_of(ccx, t);
769         call_memcpy(&B(bcx), dst, src, llsz, llalign as u32);
770     } else if common::type_is_fat_ptr(bcx.tcx(), t) {
771         let (data, extra) = load_fat_ptr(bcx, src, t);
772         store_fat_ptr(bcx, data, extra, dst, t);
773     } else {
774         store_ty(bcx, load_ty(bcx, src, t), dst, t);
775     }
776 }
777
778 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
779     if cx.unreachable.get() {
780         return;
781     }
782     let _icx = push_ctxt("init_zero_mem");
783     let bcx = cx;
784     memfill(&B(bcx), llptr, t, 0);
785 }
786
787 // Always use this function instead of storing a constant byte to the memory
788 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
789 // allocation for large data structures, and the generated code will be
790 // awful. (A telltale sign of this is large quantities of
791 // `mov [byte ptr foo],0` in the generated code.)
792 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
793     let _icx = push_ctxt("memfill");
794     let ccx = b.ccx;
795     let llty = type_of::type_of(ccx, ty);
796     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
797     let llzeroval = C_u8(ccx, byte);
798     let size = machine::llsize_of(ccx, llty);
799     let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
800     call_memset(b, llptr, llzeroval, size, align, false);
801 }
802
803 pub fn call_memset<'bcx, 'tcx>(b: &Builder<'bcx, 'tcx>,
804                                ptr: ValueRef,
805                                fill_byte: ValueRef,
806                                size: ValueRef,
807                                align: ValueRef,
808                                volatile: bool) {
809     let ccx = b.ccx;
810     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
811     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
812     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
813     let volatile = C_bool(ccx, volatile);
814     b.call(llintrinsicfn, &[ptr, fill_byte, size, align, volatile], None);
815 }
816
817 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
818                             ty: Ty<'tcx>,
819                             name: &str) -> ValueRef {
820     assert!(!ty.has_param_types());
821     alloca(bcx, type_of::type_of(bcx.ccx(), ty), name)
822 }
823
824 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
825     let _icx = push_ctxt("alloca");
826     if cx.unreachable.get() {
827         unsafe {
828             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
829         }
830     }
831     DebugLoc::None.apply(cx.fcx);
832     Alloca(cx, ty, name)
833 }
834
835 impl<'blk, 'tcx> FunctionContext<'blk, 'tcx> {
836     /// Create a function context for the given function.
837     /// Beware that you must call `fcx.init` or `fcx.bind_args`
838     /// before doing anything with the returned function context.
839     pub fn new(ccx: &'blk CrateContext<'blk, 'tcx>,
840                llfndecl: ValueRef,
841                fn_ty: FnType,
842                definition: Option<(Instance<'tcx>, &ty::FnSig<'tcx>, Abi)>,
843                block_arena: &'blk TypedArena<common::BlockS<'blk, 'tcx>>)
844                -> FunctionContext<'blk, 'tcx> {
845         let (param_substs, def_id) = match definition {
846             Some((instance, ..)) => {
847                 common::validate_substs(instance.substs);
848                 (instance.substs, Some(instance.def))
849             }
850             None => (ccx.tcx().intern_substs(&[]), None)
851         };
852
853         let local_id = def_id.and_then(|id| ccx.tcx().map.as_local_node_id(id));
854
855         debug!("FunctionContext::new({})",
856                definition.map_or(String::new(), |d| d.0.to_string()));
857
858         let no_debug = if let Some(id) = local_id {
859             ccx.tcx().map.attrs(id)
860                .iter().any(|item| item.check_name("no_debug"))
861         } else if let Some(def_id) = def_id {
862             ccx.sess().cstore.item_attrs(def_id)
863                .iter().any(|item| item.check_name("no_debug"))
864         } else {
865             false
866         };
867
868         let mir = def_id.map(|id| ccx.tcx().item_mir(id));
869
870         let debug_context = if let (false, Some((instance, sig, abi)), &Some(ref mir)) =
871                 (no_debug, definition, &mir) {
872             debuginfo::create_function_debug_context(ccx, instance, sig, abi, llfndecl, mir)
873         } else {
874             debuginfo::empty_function_debug_context(ccx)
875         };
876
877         FunctionContext {
878             mir: mir,
879             llfn: llfndecl,
880             llretslotptr: Cell::new(None),
881             param_env: ccx.tcx().empty_parameter_environment(),
882             alloca_insert_pt: Cell::new(None),
883             landingpad_alloca: Cell::new(None),
884             fn_ty: fn_ty,
885             param_substs: param_substs,
886             span: None,
887             block_arena: block_arena,
888             lpad_arena: TypedArena::new(),
889             ccx: ccx,
890             debug_context: debug_context,
891             scopes: RefCell::new(Vec::new()),
892         }
893     }
894
895     /// Performs setup on a newly created function, creating the entry
896     /// scope block and allocating space for the return pointer.
897     pub fn init(&'blk self, skip_retptr: bool) -> Block<'blk, 'tcx> {
898         let entry_bcx = self.new_block("entry-block");
899
900         // Use a dummy instruction as the insertion point for all allocas.
901         // This is later removed in FunctionContext::cleanup.
902         self.alloca_insert_pt.set(Some(unsafe {
903             Load(entry_bcx, C_null(Type::i8p(self.ccx)));
904             llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
905         }));
906
907         if !self.fn_ty.ret.is_ignore() && !skip_retptr {
908             // We normally allocate the llretslotptr, unless we
909             // have been instructed to skip it for immediate return
910             // values, or there is nothing to return at all.
911
912             // We create an alloca to hold a pointer of type `ret.original_ty`
913             // which will hold the pointer to the right alloca which has the
914             // final ret value
915             let llty = self.fn_ty.ret.memory_ty(self.ccx);
916             // But if there are no nested returns, we skip the indirection
917             // and have a single retslot
918             let slot = if self.fn_ty.ret.is_indirect() {
919                 get_param(self.llfn, 0)
920             } else {
921                 AllocaFcx(self, llty, "sret_slot")
922             };
923
924             self.llretslotptr.set(Some(slot));
925         }
926
927         entry_bcx
928     }
929
930     /// Ties up the llstaticallocas -> llloadenv -> lltop edges,
931     /// and builds the return block.
932     pub fn finish(&'blk self, ret_cx: Block<'blk, 'tcx>,
933                   ret_debug_loc: DebugLoc) {
934         let _icx = push_ctxt("FunctionContext::finish");
935
936         self.build_return_block(ret_cx, ret_debug_loc);
937
938         DebugLoc::None.apply(self);
939         self.cleanup();
940     }
941
942     // Builds the return block for a function.
943     pub fn build_return_block(&self, ret_cx: Block<'blk, 'tcx>,
944                               ret_debug_location: DebugLoc) {
945         if self.llretslotptr.get().is_none() ||
946            ret_cx.unreachable.get() ||
947            self.fn_ty.ret.is_indirect() {
948             return RetVoid(ret_cx, ret_debug_location);
949         }
950
951         let retslot = self.llretslotptr.get().unwrap();
952         let retptr = Value(retslot);
953         let llty = self.fn_ty.ret.original_ty;
954         match (retptr.get_dominating_store(ret_cx), self.fn_ty.ret.cast) {
955             // If there's only a single store to the ret slot, we can directly return
956             // the value that was stored and omit the store and the alloca.
957             // However, we only want to do this when there is no cast needed.
958             (Some(s), None) => {
959                 let mut retval = s.get_operand(0).unwrap().get();
960                 s.erase_from_parent();
961
962                 if retptr.has_no_uses() {
963                     retptr.erase_from_parent();
964                 }
965
966                 if self.fn_ty.ret.is_indirect() {
967                     Store(ret_cx, retval, get_param(self.llfn, 0));
968                     RetVoid(ret_cx, ret_debug_location)
969                 } else {
970                     if llty == Type::i1(self.ccx) {
971                         retval = Trunc(ret_cx, retval, llty);
972                     }
973                     Ret(ret_cx, retval, ret_debug_location)
974                 }
975             }
976             (_, cast_ty) if self.fn_ty.ret.is_indirect() => {
977                 // Otherwise, copy the return value to the ret slot.
978                 assert_eq!(cast_ty, None);
979                 let llsz = llsize_of(self.ccx, self.fn_ty.ret.ty);
980                 let llalign = llalign_of_min(self.ccx, self.fn_ty.ret.ty);
981                 call_memcpy(&B(ret_cx), get_param(self.llfn, 0),
982                             retslot, llsz, llalign as u32);
983                 RetVoid(ret_cx, ret_debug_location)
984             }
985             (_, Some(cast_ty)) => {
986                 let load = Load(ret_cx, PointerCast(ret_cx, retslot, cast_ty.ptr_to()));
987                 let llalign = llalign_of_min(self.ccx, self.fn_ty.ret.ty);
988                 unsafe {
989                     llvm::LLVMSetAlignment(load, llalign);
990                 }
991                 Ret(ret_cx, load, ret_debug_location)
992             }
993             (_, None) => {
994                 let retval = if llty == Type::i1(self.ccx) {
995                     let val = LoadRangeAssert(ret_cx, retslot, 0, 2, llvm::False);
996                     Trunc(ret_cx, val, llty)
997                 } else {
998                     Load(ret_cx, retslot)
999                 };
1000                 Ret(ret_cx, retval, ret_debug_location)
1001             }
1002         }
1003     }
1004 }
1005
1006 pub fn trans_instance<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, instance: Instance<'tcx>) {
1007     let _s = if ccx.sess().trans_stats() {
1008         let mut instance_name = String::new();
1009         DefPathBasedNames::new(ccx.tcx(), true, true)
1010             .push_def_path(instance.def, &mut instance_name);
1011         Some(StatRecorder::new(ccx, instance_name))
1012     } else {
1013         None
1014     };
1015
1016     // this is an info! to allow collecting monomorphization statistics
1017     // and to allow finding the last function before LLVM aborts from
1018     // release builds.
1019     info!("trans_instance({})", instance);
1020
1021     let _icx = push_ctxt("trans_instance");
1022
1023     let fn_ty = ccx.tcx().item_type(instance.def);
1024     let fn_ty = ccx.tcx().erase_regions(&fn_ty);
1025     let fn_ty = monomorphize::apply_param_substs(ccx.shared(), instance.substs, &fn_ty);
1026
1027     let ty::BareFnTy { abi, ref sig, .. } = *common::ty_fn_ty(ccx, fn_ty);
1028     let sig = ccx.tcx().erase_late_bound_regions_and_normalize(sig);
1029
1030     let lldecl = match ccx.instances().borrow().get(&instance) {
1031         Some(&val) => val,
1032         None => bug!("Instance `{:?}` not already declared", instance)
1033     };
1034
1035     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1036
1037     if !ccx.sess().no_landing_pads() {
1038         attributes::emit_uwtable(lldecl, true);
1039     }
1040
1041     let fn_ty = FnType::new(ccx, abi, &sig, &[]);
1042
1043     let (arena, fcx): (TypedArena<_>, FunctionContext);
1044     arena = TypedArena::new();
1045     fcx = FunctionContext::new(ccx,
1046                                lldecl,
1047                                fn_ty,
1048                                Some((instance, &sig, abi)),
1049                                &arena);
1050
1051     if fcx.mir.is_none() {
1052         bug!("attempted translation of `{}` w/o MIR", instance);
1053     }
1054
1055     mir::trans_mir(&fcx);
1056 }
1057
1058 pub fn trans_ctor_shim<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1059                                  def_id: DefId,
1060                                  substs: &'tcx Substs<'tcx>,
1061                                  disr: Disr,
1062                                  llfndecl: ValueRef) {
1063     attributes::inline(llfndecl, attributes::InlineAttr::Hint);
1064     attributes::set_frame_pointer_elimination(ccx, llfndecl);
1065
1066     let ctor_ty = ccx.tcx().item_type(def_id);
1067     let ctor_ty = monomorphize::apply_param_substs(ccx.shared(), substs, &ctor_ty);
1068
1069     let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&ctor_ty.fn_sig());
1070     let fn_ty = FnType::new(ccx, Abi::Rust, &sig, &[]);
1071
1072     let (arena, fcx): (TypedArena<_>, FunctionContext);
1073     arena = TypedArena::new();
1074     fcx = FunctionContext::new(ccx, llfndecl, fn_ty, None, &arena);
1075     let bcx = fcx.init(false);
1076
1077     if !fcx.fn_ty.ret.is_ignore() {
1078         let dest = fcx.llretslotptr.get().unwrap();
1079         let dest_val = adt::MaybeSizedValue::sized(dest); // Can return unsized value
1080         let mut llarg_idx = fcx.fn_ty.ret.is_indirect() as usize;
1081         let mut arg_idx = 0;
1082         for (i, arg_ty) in sig.inputs.into_iter().enumerate() {
1083             let lldestptr = adt::trans_field_ptr(bcx, sig.output, dest_val, Disr::from(disr), i);
1084             let arg = &fcx.fn_ty.args[arg_idx];
1085             arg_idx += 1;
1086             let b = &bcx.build();
1087             if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
1088                 let meta = &fcx.fn_ty.args[arg_idx];
1089                 arg_idx += 1;
1090                 arg.store_fn_arg(b, &mut llarg_idx, get_dataptr(bcx, lldestptr));
1091                 meta.store_fn_arg(b, &mut llarg_idx, get_meta(bcx, lldestptr));
1092             } else {
1093                 arg.store_fn_arg(b, &mut llarg_idx, lldestptr);
1094             }
1095         }
1096         adt::trans_set_discr(bcx, sig.output, dest, disr);
1097     }
1098
1099     fcx.finish(bcx, DebugLoc::None);
1100 }
1101
1102 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
1103     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
1104     // applicable to variable declarations and may not really make sense for
1105     // Rust code in the first place but whitelist them anyway and trust that
1106     // the user knows what s/he's doing. Who knows, unanticipated use cases
1107     // may pop up in the future.
1108     //
1109     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
1110     // and don't have to be, LLVM treats them as no-ops.
1111     match name {
1112         "appending" => Some(llvm::Linkage::AppendingLinkage),
1113         "available_externally" => Some(llvm::Linkage::AvailableExternallyLinkage),
1114         "common" => Some(llvm::Linkage::CommonLinkage),
1115         "extern_weak" => Some(llvm::Linkage::ExternalWeakLinkage),
1116         "external" => Some(llvm::Linkage::ExternalLinkage),
1117         "internal" => Some(llvm::Linkage::InternalLinkage),
1118         "linkonce" => Some(llvm::Linkage::LinkOnceAnyLinkage),
1119         "linkonce_odr" => Some(llvm::Linkage::LinkOnceODRLinkage),
1120         "private" => Some(llvm::Linkage::PrivateLinkage),
1121         "weak" => Some(llvm::Linkage::WeakAnyLinkage),
1122         "weak_odr" => Some(llvm::Linkage::WeakODRLinkage),
1123         _ => None,
1124     }
1125 }
1126
1127 pub fn set_link_section(ccx: &CrateContext,
1128                         llval: ValueRef,
1129                         attrs: &[ast::Attribute]) {
1130     if let Some(sect) = attr::first_attr_value_str_by_name(attrs, "link_section") {
1131         if contains_null(&sect) {
1132             ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
1133         }
1134         unsafe {
1135             let buf = CString::new(sect.as_bytes()).unwrap();
1136             llvm::LLVMSetSection(llval, buf.as_ptr());
1137         }
1138     }
1139 }
1140
1141 /// Create the `main` function which will initialise the rust runtime and call
1142 /// users’ main function.
1143 pub fn maybe_create_entry_wrapper(ccx: &CrateContext) {
1144     let (main_def_id, span) = match *ccx.sess().entry_fn.borrow() {
1145         Some((id, span)) => {
1146             (ccx.tcx().map.local_def_id(id), span)
1147         }
1148         None => return,
1149     };
1150
1151     // check for the #[rustc_error] annotation, which forces an
1152     // error in trans. This is used to write compile-fail tests
1153     // that actually test that compilation succeeds without
1154     // reporting an error.
1155     if ccx.tcx().has_attr(main_def_id, "rustc_error") {
1156         ccx.tcx().sess.span_fatal(span, "compilation successful");
1157     }
1158
1159     let instance = Instance::mono(ccx.shared(), main_def_id);
1160
1161     if !ccx.codegen_unit().contains_item(&TransItem::Fn(instance)) {
1162         // We want to create the wrapper in the same codegen unit as Rust's main
1163         // function.
1164         return;
1165     }
1166
1167     let main_llfn = Callee::def(ccx, main_def_id, instance.substs).reify(ccx);
1168
1169     let et = ccx.sess().entry_type.get().unwrap();
1170     match et {
1171         config::EntryMain => {
1172             create_entry_fn(ccx, span, main_llfn, true);
1173         }
1174         config::EntryStart => create_entry_fn(ccx, span, main_llfn, false),
1175         config::EntryNone => {}    // Do nothing.
1176     }
1177
1178     fn create_entry_fn(ccx: &CrateContext,
1179                        sp: Span,
1180                        rust_main: ValueRef,
1181                        use_start_lang_item: bool) {
1182         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
1183
1184         if declare::get_defined_value(ccx, "main").is_some() {
1185             // FIXME: We should be smart and show a better diagnostic here.
1186             ccx.sess().struct_span_err(sp, "entry symbol `main` defined multiple times")
1187                       .help("did you use #[no_mangle] on `fn main`? Use #[start] instead")
1188                       .emit();
1189             ccx.sess().abort_if_errors();
1190             bug!();
1191         }
1192         let llfn = declare::declare_cfn(ccx, "main", llfty);
1193
1194         // `main` should respect same config for frame pointer elimination as rest of code
1195         attributes::set_frame_pointer_elimination(ccx, llfn);
1196
1197         let llbb = unsafe {
1198             llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, "top\0".as_ptr() as *const _)
1199         };
1200         let bld = ccx.raw_builder();
1201         unsafe {
1202             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1203
1204             debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
1205
1206             let (start_fn, args) = if use_start_lang_item {
1207                 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
1208                     Ok(id) => id,
1209                     Err(s) => ccx.sess().fatal(&s)
1210                 };
1211                 let empty_substs = ccx.tcx().intern_substs(&[]);
1212                 let start_fn = Callee::def(ccx, start_def_id, empty_substs).reify(ccx);
1213                 let args = {
1214                     let opaque_rust_main =
1215                         llvm::LLVMBuildPointerCast(bld,
1216                                                    rust_main,
1217                                                    Type::i8p(ccx).to_ref(),
1218                                                    "rust_main\0".as_ptr() as *const _);
1219
1220                     vec![opaque_rust_main, get_param(llfn, 0), get_param(llfn, 1)]
1221                 };
1222                 (start_fn, args)
1223             } else {
1224                 debug!("using user-defined start fn");
1225                 let args = vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)];
1226
1227                 (rust_main, args)
1228             };
1229
1230             let result = llvm::LLVMRustBuildCall(bld,
1231                                                  start_fn,
1232                                                  args.as_ptr(),
1233                                                  args.len() as c_uint,
1234                                                  ptr::null_mut(),
1235                                                  noname());
1236
1237             llvm::LLVMBuildRet(bld, result);
1238         }
1239     }
1240 }
1241
1242 fn contains_null(s: &str) -> bool {
1243     s.bytes().any(|b| b == 0)
1244 }
1245
1246 fn write_metadata(cx: &SharedCrateContext,
1247                   reachable_ids: &NodeSet) -> Vec<u8> {
1248     use flate;
1249
1250     #[derive(PartialEq, Eq, PartialOrd, Ord)]
1251     enum MetadataKind {
1252         None,
1253         Uncompressed,
1254         Compressed
1255     }
1256
1257     let kind = cx.sess().crate_types.borrow().iter().map(|ty| {
1258         match *ty {
1259             config::CrateTypeExecutable |
1260             config::CrateTypeStaticlib |
1261             config::CrateTypeCdylib => MetadataKind::None,
1262
1263             config::CrateTypeRlib |
1264             config::CrateTypeMetadata => MetadataKind::Uncompressed,
1265
1266             config::CrateTypeDylib |
1267             config::CrateTypeProcMacro => MetadataKind::Compressed,
1268         }
1269     }).max().unwrap();
1270
1271     if kind == MetadataKind::None {
1272         return Vec::new();
1273     }
1274
1275     let cstore = &cx.tcx().sess.cstore;
1276     let metadata = cstore.encode_metadata(cx.tcx(),
1277                                           cx.export_map(),
1278                                           cx.link_meta(),
1279                                           reachable_ids);
1280     if kind == MetadataKind::Uncompressed {
1281         return metadata;
1282     }
1283
1284     assert!(kind == MetadataKind::Compressed);
1285     let mut compressed = cstore.metadata_encoding_version().to_vec();
1286     compressed.extend_from_slice(&flate::deflate_bytes(&metadata));
1287
1288     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
1289     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
1290     let name = cx.metadata_symbol_name();
1291     let buf = CString::new(name).unwrap();
1292     let llglobal = unsafe {
1293         llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
1294     };
1295     unsafe {
1296         llvm::LLVMSetInitializer(llglobal, llconst);
1297         let section_name =
1298             cx.tcx().sess.cstore.metadata_section_name(&cx.sess().target.target);
1299         let name = CString::new(section_name).unwrap();
1300         llvm::LLVMSetSection(llglobal, name.as_ptr());
1301
1302         // Also generate a .section directive to force no
1303         // flags, at least for ELF outputs, so that the
1304         // metadata doesn't get loaded into memory.
1305         let directive = format!(".section {}", section_name);
1306         let directive = CString::new(directive).unwrap();
1307         llvm::LLVMSetModuleInlineAsm(cx.metadata_llmod(), directive.as_ptr())
1308     }
1309     return metadata;
1310 }
1311
1312 /// Find any symbols that are defined in one compilation unit, but not declared
1313 /// in any other compilation unit.  Give these symbols internal linkage.
1314 fn internalize_symbols<'a, 'tcx>(sess: &Session,
1315                                  ccxs: &CrateContextList<'a, 'tcx>,
1316                                  symbol_map: &SymbolMap<'tcx>,
1317                                  reachable: &FxHashSet<&str>) {
1318     let scx = ccxs.shared();
1319     let tcx = scx.tcx();
1320
1321     // In incr. comp. mode, we can't necessarily see all refs since we
1322     // don't generate LLVM IR for reused modules, so skip this
1323     // step. Later we should get smarter.
1324     if sess.opts.debugging_opts.incremental.is_some() {
1325         return;
1326     }
1327
1328     // 'unsafe' because we are holding on to CStr's from the LLVM module within
1329     // this block.
1330     unsafe {
1331         let mut referenced_somewhere = FxHashSet();
1332
1333         // Collect all symbols that need to stay externally visible because they
1334         // are referenced via a declaration in some other codegen unit.
1335         for ccx in ccxs.iter_need_trans() {
1336             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
1337                 let linkage = llvm::LLVMRustGetLinkage(val);
1338                 // We only care about external declarations (not definitions)
1339                 // and available_externally definitions.
1340                 let is_available_externally = linkage == llvm::Linkage::AvailableExternallyLinkage;
1341                 let is_decl = llvm::LLVMIsDeclaration(val) != 0;
1342
1343                 if is_decl || is_available_externally {
1344                     let symbol_name = CStr::from_ptr(llvm::LLVMGetValueName(val));
1345                     referenced_somewhere.insert(symbol_name);
1346                 }
1347             }
1348         }
1349
1350         // Also collect all symbols for which we cannot adjust linkage, because
1351         // it is fixed by some directive in the source code (e.g. #[no_mangle]).
1352         let linkage_fixed_explicitly: FxHashSet<_> = scx
1353             .translation_items()
1354             .borrow()
1355             .iter()
1356             .cloned()
1357             .filter(|trans_item|{
1358                 trans_item.explicit_linkage(tcx).is_some()
1359             })
1360             .map(|trans_item| symbol_map.get_or_compute(scx, trans_item))
1361             .collect();
1362
1363         // Examine each external definition.  If the definition is not used in
1364         // any other compilation unit, and is not reachable from other crates,
1365         // then give it internal linkage.
1366         for ccx in ccxs.iter_need_trans() {
1367             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
1368                 let linkage = llvm::LLVMRustGetLinkage(val);
1369
1370                 let is_externally_visible = (linkage == llvm::Linkage::ExternalLinkage) ||
1371                                             (linkage == llvm::Linkage::LinkOnceODRLinkage) ||
1372                                             (linkage == llvm::Linkage::WeakODRLinkage);
1373                 let is_definition = llvm::LLVMIsDeclaration(val) == 0;
1374
1375                 // If this is a definition (as opposed to just a declaration)
1376                 // and externally visible, check if we can internalize it
1377                 if is_definition && is_externally_visible {
1378                     let name_cstr = CStr::from_ptr(llvm::LLVMGetValueName(val));
1379                     let name_str = name_cstr.to_str().unwrap();
1380                     let name_cow = Cow::Borrowed(name_str);
1381
1382                     let is_referenced_somewhere = referenced_somewhere.contains(&name_cstr);
1383                     let is_reachable = reachable.contains(&name_str);
1384                     let has_fixed_linkage = linkage_fixed_explicitly.contains(&name_cow);
1385
1386                     if !is_referenced_somewhere && !is_reachable && !has_fixed_linkage {
1387                         llvm::LLVMRustSetLinkage(val, llvm::Linkage::InternalLinkage);
1388                         llvm::LLVMSetDLLStorageClass(val,
1389                                                      llvm::DLLStorageClass::Default);
1390                         llvm::UnsetComdat(val);
1391                     }
1392                 }
1393             }
1394         }
1395     }
1396 }
1397
1398 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
1399 // This is required to satisfy `dllimport` references to static data in .rlibs
1400 // when using MSVC linker.  We do this only for data, as linker can fix up
1401 // code references on its own.
1402 // See #26591, #27438
1403 fn create_imps(cx: &CrateContextList) {
1404     // The x86 ABI seems to require that leading underscores are added to symbol
1405     // names, so we need an extra underscore on 32-bit. There's also a leading
1406     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
1407     // underscores added in front).
1408     let prefix = if cx.shared().sess().target.target.target_pointer_width == "32" {
1409         "\x01__imp__"
1410     } else {
1411         "\x01__imp_"
1412     };
1413     unsafe {
1414         for ccx in cx.iter_need_trans() {
1415             let exported: Vec<_> = iter_globals(ccx.llmod())
1416                                        .filter(|&val| {
1417                                            llvm::LLVMRustGetLinkage(val) ==
1418                                            llvm::Linkage::ExternalLinkage &&
1419                                            llvm::LLVMIsDeclaration(val) == 0
1420                                        })
1421                                        .collect();
1422
1423             let i8p_ty = Type::i8p(&ccx);
1424             for val in exported {
1425                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
1426                 let mut imp_name = prefix.as_bytes().to_vec();
1427                 imp_name.extend(name.to_bytes());
1428                 let imp_name = CString::new(imp_name).unwrap();
1429                 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
1430                                               i8p_ty.to_ref(),
1431                                               imp_name.as_ptr() as *const _);
1432                 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
1433                 llvm::LLVMSetInitializer(imp, init);
1434                 llvm::LLVMRustSetLinkage(imp, llvm::Linkage::ExternalLinkage);
1435             }
1436         }
1437     }
1438 }
1439
1440 struct ValueIter {
1441     cur: ValueRef,
1442     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
1443 }
1444
1445 impl Iterator for ValueIter {
1446     type Item = ValueRef;
1447
1448     fn next(&mut self) -> Option<ValueRef> {
1449         let old = self.cur;
1450         if !old.is_null() {
1451             self.cur = unsafe { (self.step)(old) };
1452             Some(old)
1453         } else {
1454             None
1455         }
1456     }
1457 }
1458
1459 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
1460     unsafe {
1461         ValueIter {
1462             cur: llvm::LLVMGetFirstGlobal(llmod),
1463             step: llvm::LLVMGetNextGlobal,
1464         }
1465     }
1466 }
1467
1468 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
1469     unsafe {
1470         ValueIter {
1471             cur: llvm::LLVMGetFirstFunction(llmod),
1472             step: llvm::LLVMGetNextFunction,
1473         }
1474     }
1475 }
1476
1477 /// The context provided lists a set of reachable ids as calculated by
1478 /// middle::reachable, but this contains far more ids and symbols than we're
1479 /// actually exposing from the object file. This function will filter the set in
1480 /// the context to the set of ids which correspond to symbols that are exposed
1481 /// from the object file being generated.
1482 ///
1483 /// This list is later used by linkers to determine the set of symbols needed to
1484 /// be exposed from a dynamic library and it's also encoded into the metadata.
1485 pub fn filter_reachable_ids(tcx: TyCtxt, reachable: NodeSet) -> NodeSet {
1486     reachable.into_iter().filter(|&id| {
1487         // Next, we want to ignore some FFI functions that are not exposed from
1488         // this crate. Reachable FFI functions can be lumped into two
1489         // categories:
1490         //
1491         // 1. Those that are included statically via a static library
1492         // 2. Those included otherwise (e.g. dynamically or via a framework)
1493         //
1494         // Although our LLVM module is not literally emitting code for the
1495         // statically included symbols, it's an export of our library which
1496         // needs to be passed on to the linker and encoded in the metadata.
1497         //
1498         // As a result, if this id is an FFI item (foreign item) then we only
1499         // let it through if it's included statically.
1500         match tcx.map.get(id) {
1501             hir_map::NodeForeignItem(..) => {
1502                 tcx.sess.cstore.is_statically_included_foreign_item(id)
1503             }
1504
1505             // Only consider nodes that actually have exported symbols.
1506             hir_map::NodeItem(&hir::Item {
1507                 node: hir::ItemStatic(..), .. }) |
1508             hir_map::NodeItem(&hir::Item {
1509                 node: hir::ItemFn(..), .. }) |
1510             hir_map::NodeImplItem(&hir::ImplItem {
1511                 node: hir::ImplItemKind::Method(..), .. }) => {
1512                 let def_id = tcx.map.local_def_id(id);
1513                 let generics = tcx.item_generics(def_id);
1514                 let attributes = tcx.get_attrs(def_id);
1515                 (generics.parent_types == 0 && generics.types.is_empty()) &&
1516                 // Functions marked with #[inline] are only ever translated
1517                 // with "internal" linkage and are never exported.
1518                 !attr::requests_inline(&attributes[..])
1519             }
1520
1521             _ => false
1522         }
1523     }).collect()
1524 }
1525
1526 pub fn trans_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1527                              analysis: ty::CrateAnalysis,
1528                              incremental_hashes_map: &IncrementalHashesMap)
1529                              -> CrateTranslation {
1530     let _task = tcx.dep_graph.in_task(DepNode::TransCrate);
1531
1532     // Be careful with this krate: obviously it gives access to the
1533     // entire contents of the krate. So if you push any subtasks of
1534     // `TransCrate`, you need to be careful to register "reads" of the
1535     // particular items that will be processed.
1536     let krate = tcx.map.krate();
1537
1538     let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
1539     let reachable = filter_reachable_ids(tcx, reachable);
1540
1541     let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
1542         v
1543     } else {
1544         tcx.sess.opts.debug_assertions
1545     };
1546
1547     let link_meta = link::build_link_meta(incremental_hashes_map, name);
1548
1549     let shared_ccx = SharedCrateContext::new(tcx,
1550                                              export_map,
1551                                              link_meta.clone(),
1552                                              reachable,
1553                                              check_overflow);
1554     // Translate the metadata.
1555     let metadata = time(tcx.sess.time_passes(), "write metadata", || {
1556         write_metadata(&shared_ccx, shared_ccx.reachable())
1557     });
1558
1559     let metadata_module = ModuleTranslation {
1560         name: "metadata".to_string(),
1561         symbol_name_hash: 0, // we always rebuild metadata, at least for now
1562         source: ModuleSource::Translated(ModuleLlvm {
1563             llcx: shared_ccx.metadata_llcx(),
1564             llmod: shared_ccx.metadata_llmod(),
1565         }),
1566     };
1567     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
1568
1569     // Run the translation item collector and partition the collected items into
1570     // codegen units.
1571     let (codegen_units, symbol_map) = collect_and_partition_translation_items(&shared_ccx);
1572
1573     let symbol_map = Rc::new(symbol_map);
1574
1575     let previous_work_products = trans_reuse_previous_work_products(tcx,
1576                                                                     &codegen_units,
1577                                                                     &symbol_map);
1578
1579     let crate_context_list = CrateContextList::new(&shared_ccx,
1580                                                    codegen_units,
1581                                                    previous_work_products,
1582                                                    symbol_map.clone());
1583     let modules: Vec<_> = crate_context_list.iter_all()
1584         .map(|ccx| {
1585             let source = match ccx.previous_work_product() {
1586                 Some(buf) => ModuleSource::Preexisting(buf.clone()),
1587                 None => ModuleSource::Translated(ModuleLlvm {
1588                     llcx: ccx.llcx(),
1589                     llmod: ccx.llmod(),
1590                 }),
1591             };
1592
1593             ModuleTranslation {
1594                 name: String::from(ccx.codegen_unit().name()),
1595                 symbol_name_hash: ccx.codegen_unit().compute_symbol_name_hash(tcx, &symbol_map),
1596                 source: source,
1597             }
1598         })
1599         .collect();
1600
1601     assert_module_sources::assert_module_sources(tcx, &modules);
1602
1603     // Skip crate items and just output metadata in -Z no-trans mode.
1604     if tcx.sess.opts.debugging_opts.no_trans ||
1605        tcx.sess.crate_types.borrow().iter().all(|ct| ct == &config::CrateTypeMetadata) {
1606         let linker_info = LinkerInfo::new(&shared_ccx, &[]);
1607         return CrateTranslation {
1608             modules: modules,
1609             metadata_module: metadata_module,
1610             link: link_meta,
1611             metadata: metadata,
1612             reachable: vec![],
1613             no_builtins: no_builtins,
1614             linker_info: linker_info,
1615             windows_subsystem: None,
1616         };
1617     }
1618
1619     // Instantiate translation items without filling out definitions yet...
1620     for ccx in crate_context_list.iter_need_trans() {
1621         let cgu = ccx.codegen_unit();
1622         let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
1623
1624         tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
1625             for (trans_item, linkage) in trans_items {
1626                 trans_item.predefine(&ccx, linkage);
1627             }
1628         });
1629     }
1630
1631     // ... and now that we have everything pre-defined, fill out those definitions.
1632     for ccx in crate_context_list.iter_need_trans() {
1633         let cgu = ccx.codegen_unit();
1634         let trans_items = cgu.items_in_deterministic_order(tcx, &symbol_map);
1635         tcx.dep_graph.with_task(cgu.work_product_dep_node(), || {
1636             for (trans_item, _) in trans_items {
1637                 trans_item.define(&ccx);
1638             }
1639
1640             // If this codegen unit contains the main function, also create the
1641             // wrapper here
1642             maybe_create_entry_wrapper(&ccx);
1643
1644             // Run replace-all-uses-with for statics that need it
1645             for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
1646                 unsafe {
1647                     let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
1648                     llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
1649                     llvm::LLVMDeleteGlobal(old_g);
1650                 }
1651             }
1652
1653             // Finalize debuginfo
1654             if ccx.sess().opts.debuginfo != NoDebugInfo {
1655                 debuginfo::finalize(&ccx);
1656             }
1657         });
1658     }
1659
1660     symbol_names_test::report_symbol_names(&shared_ccx);
1661
1662     if shared_ccx.sess().trans_stats() {
1663         let stats = shared_ccx.stats();
1664         println!("--- trans stats ---");
1665         println!("n_glues_created: {}", stats.n_glues_created.get());
1666         println!("n_null_glues: {}", stats.n_null_glues.get());
1667         println!("n_real_glues: {}", stats.n_real_glues.get());
1668
1669         println!("n_fns: {}", stats.n_fns.get());
1670         println!("n_inlines: {}", stats.n_inlines.get());
1671         println!("n_closures: {}", stats.n_closures.get());
1672         println!("fn stats:");
1673         stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
1674             insns_b.cmp(&insns_a)
1675         });
1676         for tuple in stats.fn_stats.borrow().iter() {
1677             match *tuple {
1678                 (ref name, insns) => {
1679                     println!("{} insns, {}", insns, *name);
1680                 }
1681             }
1682         }
1683     }
1684
1685     if shared_ccx.sess().count_llvm_insns() {
1686         for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
1687             println!("{:7} {}", *v, *k);
1688         }
1689     }
1690
1691     let sess = shared_ccx.sess();
1692     let mut reachable_symbols = shared_ccx.reachable().iter().map(|&id| {
1693         let def_id = shared_ccx.tcx().map.local_def_id(id);
1694         symbol_for_def_id(def_id, &shared_ccx, &symbol_map)
1695     }).collect::<Vec<_>>();
1696
1697     if sess.entry_fn.borrow().is_some() {
1698         reachable_symbols.push("main".to_string());
1699     }
1700
1701     if sess.crate_types.borrow().contains(&config::CrateTypeDylib) {
1702         reachable_symbols.push(shared_ccx.metadata_symbol_name());
1703     }
1704
1705     // For the purposes of LTO or when creating a cdylib, we add to the
1706     // reachable set all of the upstream reachable extern fns. These functions
1707     // are all part of the public ABI of the final product, so we need to
1708     // preserve them.
1709     //
1710     // Note that this happens even if LTO isn't requested or we're not creating
1711     // a cdylib. In those cases, though, we're not even reading the
1712     // `reachable_symbols` list later on so it should be ok.
1713     for cnum in sess.cstore.crates() {
1714         let syms = sess.cstore.reachable_ids(cnum);
1715         reachable_symbols.extend(syms.into_iter().filter(|&def_id| {
1716             let applicable = match sess.cstore.describe_def(def_id) {
1717                 Some(Def::Static(..)) => true,
1718                 Some(Def::Fn(_)) => {
1719                     shared_ccx.tcx().item_generics(def_id).types.is_empty()
1720                 }
1721                 _ => false
1722             };
1723
1724             if applicable {
1725                 let attrs = shared_ccx.tcx().get_attrs(def_id);
1726                 attr::contains_extern_indicator(sess.diagnostic(), &attrs)
1727             } else {
1728                 false
1729             }
1730         }).map(|did| {
1731             symbol_for_def_id(did, &shared_ccx, &symbol_map)
1732         }));
1733     }
1734
1735     time(shared_ccx.sess().time_passes(), "internalize symbols", || {
1736         internalize_symbols(sess,
1737                             &crate_context_list,
1738                             &symbol_map,
1739                             &reachable_symbols.iter()
1740                                               .map(|s| &s[..])
1741                                               .collect())
1742     });
1743
1744     if sess.target.target.options.is_like_msvc &&
1745        sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
1746         create_imps(&crate_context_list);
1747     }
1748
1749     let linker_info = LinkerInfo::new(&shared_ccx, &reachable_symbols);
1750
1751     let subsystem = attr::first_attr_value_str_by_name(&krate.attrs,
1752                                                        "windows_subsystem");
1753     let windows_subsystem = subsystem.map(|subsystem| {
1754         if subsystem != "windows" && subsystem != "console" {
1755             tcx.sess.fatal(&format!("invalid windows subsystem `{}`, only \
1756                                      `windows` and `console` are allowed",
1757                                     subsystem));
1758         }
1759         subsystem.to_string()
1760     });
1761
1762     CrateTranslation {
1763         modules: modules,
1764         metadata_module: metadata_module,
1765         link: link_meta,
1766         metadata: metadata,
1767         reachable: reachable_symbols,
1768         no_builtins: no_builtins,
1769         linker_info: linker_info,
1770         windows_subsystem: windows_subsystem,
1771     }
1772 }
1773
1774 /// For each CGU, identify if we can reuse an existing object file (or
1775 /// maybe other context).
1776 fn trans_reuse_previous_work_products(tcx: TyCtxt,
1777                                       codegen_units: &[CodegenUnit],
1778                                       symbol_map: &SymbolMap)
1779                                       -> Vec<Option<WorkProduct>> {
1780     debug!("trans_reuse_previous_work_products()");
1781     codegen_units
1782         .iter()
1783         .map(|cgu| {
1784             let id = cgu.work_product_id();
1785
1786             let hash = cgu.compute_symbol_name_hash(tcx, symbol_map);
1787
1788             debug!("trans_reuse_previous_work_products: id={:?} hash={}", id, hash);
1789
1790             if let Some(work_product) = tcx.dep_graph.previous_work_product(&id) {
1791                 if work_product.input_hash == hash {
1792                     debug!("trans_reuse_previous_work_products: reusing {:?}", work_product);
1793                     return Some(work_product);
1794                 } else {
1795                     debug!("trans_reuse_previous_work_products: \
1796                             not reusing {:?} because hash changed to {:?}",
1797                            work_product, hash);
1798                 }
1799             }
1800
1801             None
1802         })
1803         .collect()
1804 }
1805
1806 fn collect_and_partition_translation_items<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>)
1807                                                      -> (Vec<CodegenUnit<'tcx>>, SymbolMap<'tcx>) {
1808     let time_passes = scx.sess().time_passes();
1809
1810     let collection_mode = match scx.sess().opts.debugging_opts.print_trans_items {
1811         Some(ref s) => {
1812             let mode_string = s.to_lowercase();
1813             let mode_string = mode_string.trim();
1814             if mode_string == "eager" {
1815                 TransItemCollectionMode::Eager
1816             } else {
1817                 if mode_string != "lazy" {
1818                     let message = format!("Unknown codegen-item collection mode '{}'. \
1819                                            Falling back to 'lazy' mode.",
1820                                            mode_string);
1821                     scx.sess().warn(&message);
1822                 }
1823
1824                 TransItemCollectionMode::Lazy
1825             }
1826         }
1827         None => TransItemCollectionMode::Lazy
1828     };
1829
1830     let (items, inlining_map) =
1831         time(time_passes, "translation item collection", || {
1832             collector::collect_crate_translation_items(&scx, collection_mode)
1833     });
1834
1835     let symbol_map = SymbolMap::build(scx, items.iter().cloned());
1836
1837     let strategy = if scx.sess().opts.debugging_opts.incremental.is_some() {
1838         PartitioningStrategy::PerModule
1839     } else {
1840         PartitioningStrategy::FixedUnitCount(scx.sess().opts.cg.codegen_units)
1841     };
1842
1843     let codegen_units = time(time_passes, "codegen unit partitioning", || {
1844         partitioning::partition(scx,
1845                                 items.iter().cloned(),
1846                                 strategy,
1847                                 &inlining_map)
1848     });
1849
1850     assert!(scx.tcx().sess.opts.cg.codegen_units == codegen_units.len() ||
1851             scx.tcx().sess.opts.debugging_opts.incremental.is_some());
1852
1853     {
1854         let mut ccx_map = scx.translation_items().borrow_mut();
1855
1856         for trans_item in items.iter().cloned() {
1857             ccx_map.insert(trans_item);
1858         }
1859     }
1860
1861     if scx.sess().opts.debugging_opts.print_trans_items.is_some() {
1862         let mut item_to_cgus = FxHashMap();
1863
1864         for cgu in &codegen_units {
1865             for (&trans_item, &linkage) in cgu.items() {
1866                 item_to_cgus.entry(trans_item)
1867                             .or_insert(Vec::new())
1868                             .push((cgu.name().clone(), linkage));
1869             }
1870         }
1871
1872         let mut item_keys: Vec<_> = items
1873             .iter()
1874             .map(|i| {
1875                 let mut output = i.to_string(scx.tcx());
1876                 output.push_str(" @@");
1877                 let mut empty = Vec::new();
1878                 let mut cgus = item_to_cgus.get_mut(i).unwrap_or(&mut empty);
1879                 cgus.as_mut_slice().sort_by_key(|&(ref name, _)| name.clone());
1880                 cgus.dedup();
1881                 for &(ref cgu_name, linkage) in cgus.iter() {
1882                     output.push_str(" ");
1883                     output.push_str(&cgu_name[..]);
1884
1885                     let linkage_abbrev = match linkage {
1886                         llvm::Linkage::ExternalLinkage => "External",
1887                         llvm::Linkage::AvailableExternallyLinkage => "Available",
1888                         llvm::Linkage::LinkOnceAnyLinkage => "OnceAny",
1889                         llvm::Linkage::LinkOnceODRLinkage => "OnceODR",
1890                         llvm::Linkage::WeakAnyLinkage => "WeakAny",
1891                         llvm::Linkage::WeakODRLinkage => "WeakODR",
1892                         llvm::Linkage::AppendingLinkage => "Appending",
1893                         llvm::Linkage::InternalLinkage => "Internal",
1894                         llvm::Linkage::PrivateLinkage => "Private",
1895                         llvm::Linkage::ExternalWeakLinkage => "ExternalWeak",
1896                         llvm::Linkage::CommonLinkage => "Common",
1897                     };
1898
1899                     output.push_str("[");
1900                     output.push_str(linkage_abbrev);
1901                     output.push_str("]");
1902                 }
1903                 output
1904             })
1905             .collect();
1906
1907         item_keys.sort();
1908
1909         for item in item_keys {
1910             println!("TRANS_ITEM {}", item);
1911         }
1912     }
1913
1914     (codegen_units, symbol_map)
1915 }
1916
1917 fn symbol_for_def_id<'a, 'tcx>(def_id: DefId,
1918                                scx: &SharedCrateContext<'a, 'tcx>,
1919                                symbol_map: &SymbolMap<'tcx>)
1920                                -> String {
1921     // Just try to look things up in the symbol map. If nothing's there, we
1922     // recompute.
1923     if let Some(node_id) = scx.tcx().map.as_local_node_id(def_id) {
1924         if let Some(sym) = symbol_map.get(TransItem::Static(node_id)) {
1925             return sym.to_owned();
1926         }
1927     }
1928
1929     let instance = Instance::mono(scx, def_id);
1930
1931     symbol_map.get(TransItem::Fn(instance))
1932               .map(str::to_owned)
1933               .unwrap_or_else(|| instance.symbol_name(scx))
1934 }