]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/base.rs
0af47550d758d7c7871f663f23306d7cfbcda793
[rust.git] / src / librustc_trans / 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 //! Translate the completed AST to the LLVM IR.
11 //!
12 //! Some functions here, such as trans_block and trans_expr, return a value --
13 //! the result of the translation to LLVM -- while others, such as trans_fn,
14 //! trans_impl, and trans_item, are called only for the side effect of adding a
15 //! particular definition to the LLVM IR output we're producing.
16 //!
17 //! Hopefully useful general knowledge about trans:
18 //!
19 //!   * There's no way to find out the Ty type of a ValueRef.  Doing so
20 //!     would be "trying to get the eggs out of an omelette" (credit:
21 //!     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
22 //!     but one TypeRef corresponds to many `Ty`s; for instance, tup(int, int,
23 //!     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
24
25 #![allow(non_camel_case_types)]
26
27 pub use self::ValueOrigin::*;
28
29 use super::CrateTranslation;
30 use super::ModuleTranslation;
31
32 use back::link::mangle_exported_name;
33 use back::{link, abi};
34 use lint;
35 use llvm::{BasicBlockRef, Linkage, ValueRef, Vector, get_param};
36 use llvm;
37 use metadata::{csearch, encoder, loader};
38 use middle::astencode;
39 use middle::cfg;
40 use middle::def_id::DefId;
41 use middle::infer;
42 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
43 use middle::weak_lang_items;
44 use middle::pat_util::simple_name;
45 use middle::subst::Substs;
46 use middle::ty::{self, Ty, HasTypeFlags};
47 use rustc::front::map as hir_map;
48 use rustc_mir::mir_map::MirMap;
49 use session::config::{self, NoDebugInfo, FullDebugInfo};
50 use session::Session;
51 use trans::_match;
52 use trans::adt;
53 use trans::attributes;
54 use trans::build::*;
55 use trans::builder::{Builder, noname};
56 use trans::callee;
57 use trans::cleanup::{self, CleanupMethods, DropHint};
58 use trans::closure;
59 use trans::common::{Block, C_bool, C_bytes_in_context, C_i32, C_int, C_uint, C_integral};
60 use trans::common::{C_null, C_struct_in_context, C_u64, C_u8, C_undef};
61 use trans::common::{CrateContext, DropFlagHintsMap, Field, FunctionContext};
62 use trans::common::{Result, NodeIdAndSpan, VariantInfo};
63 use trans::common::{node_id_type, return_type_is_void};
64 use trans::common::{type_is_immediate, type_is_zero_size, val_ty};
65 use trans::common;
66 use trans::consts;
67 use trans::context::SharedCrateContext;
68 use trans::controlflow;
69 use trans::datum;
70 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
71 use trans::declare;
72 use trans::expr;
73 use trans::foreign;
74 use trans::glue;
75 use trans::intrinsic;
76 use trans::machine;
77 use trans::machine::{llsize_of, llsize_of_real};
78 use trans::meth;
79 use trans::mir;
80 use trans::monomorphize;
81 use trans::tvec;
82 use trans::type_::Type;
83 use trans::type_of;
84 use trans::type_of::*;
85 use trans::value::Value;
86 use util::common::indenter;
87 use util::sha2::Sha256;
88 use util::nodemap::{NodeMap, NodeSet};
89
90 use arena::TypedArena;
91 use libc::c_uint;
92 use std::ffi::{CStr, CString};
93 use std::cell::{Cell, RefCell};
94 use std::collections::{HashMap, HashSet};
95 use std::str;
96 use std::{i8, i16, i32, i64};
97 use syntax::abi::{Rust, RustCall, RustIntrinsic, PlatformIntrinsic, Abi};
98 use syntax::codemap::Span;
99 use syntax::parse::token::InternedString;
100 use syntax::attr::AttrMetaMethods;
101 use syntax::attr;
102 use rustc_front;
103 use rustc_front::intravisit::{self, Visitor};
104 use rustc_front::hir;
105 use syntax::ast;
106
107 thread_local! {
108     static TASK_LOCAL_INSN_KEY: RefCell<Option<Vec<&'static str>>> = {
109         RefCell::new(None)
110     }
111 }
112
113 pub fn with_insn_ctxt<F>(blk: F)
114     where F: FnOnce(&[&'static str])
115 {
116     TASK_LOCAL_INSN_KEY.with(move |slot| {
117         slot.borrow().as_ref().map(move |s| blk(s));
118     })
119 }
120
121 pub fn init_insn_ctxt() {
122     TASK_LOCAL_INSN_KEY.with(|slot| {
123         *slot.borrow_mut() = Some(Vec::new());
124     });
125 }
126
127 pub struct _InsnCtxt {
128     _cannot_construct_outside_of_this_module: (),
129 }
130
131 impl Drop for _InsnCtxt {
132     fn drop(&mut self) {
133         TASK_LOCAL_INSN_KEY.with(|slot| {
134             match slot.borrow_mut().as_mut() {
135                 Some(ctx) => {
136                     ctx.pop();
137                 }
138                 None => {}
139             }
140         })
141     }
142 }
143
144 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
145     debug!("new InsnCtxt: {}", s);
146     TASK_LOCAL_INSN_KEY.with(|slot| {
147         match slot.borrow_mut().as_mut() {
148             Some(ctx) => ctx.push(s),
149             None => {}
150         }
151     });
152     _InsnCtxt {
153         _cannot_construct_outside_of_this_module: (),
154     }
155 }
156
157 pub struct StatRecorder<'a, 'tcx: 'a> {
158     ccx: &'a CrateContext<'a, 'tcx>,
159     name: Option<String>,
160     istart: usize,
161 }
162
163 impl<'a, 'tcx> StatRecorder<'a, 'tcx> {
164     pub fn new(ccx: &'a CrateContext<'a, 'tcx>, name: String) -> StatRecorder<'a, 'tcx> {
165         let istart = ccx.stats().n_llvm_insns.get();
166         StatRecorder {
167             ccx: ccx,
168             name: Some(name),
169             istart: istart,
170         }
171     }
172 }
173
174 impl<'a, 'tcx> Drop for StatRecorder<'a, 'tcx> {
175     fn drop(&mut self) {
176         if self.ccx.sess().trans_stats() {
177             let iend = self.ccx.stats().n_llvm_insns.get();
178             self.ccx
179                 .stats()
180                 .fn_stats
181                 .borrow_mut()
182                 .push((self.name.take().unwrap(), iend - self.istart));
183             self.ccx.stats().n_fns.set(self.ccx.stats().n_fns.get() + 1);
184             // Reset LLVM insn count to avoid compound costs.
185             self.ccx.stats().n_llvm_insns.set(self.istart);
186         }
187     }
188 }
189
190 fn get_extern_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
191                                 fn_ty: Ty<'tcx>,
192                                 name: &str,
193                                 did: DefId)
194                                 -> ValueRef {
195     match ccx.externs().borrow().get(name) {
196         Some(n) => return *n,
197         None => (),
198     }
199
200     let f = declare::declare_rust_fn(ccx, name, fn_ty);
201
202     let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
203     attributes::from_fn_attrs(ccx, &attrs[..], f);
204
205     ccx.externs().borrow_mut().insert(name.to_string(), f);
206     f
207 }
208
209 pub fn self_type_for_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
210                                        closure_id: DefId,
211                                        fn_ty: Ty<'tcx>)
212                                        -> Ty<'tcx> {
213     let closure_kind = ccx.tcx().closure_kind(closure_id);
214     match closure_kind {
215         ty::FnClosureKind => {
216             ccx.tcx().mk_imm_ref(ccx.tcx().mk_region(ty::ReStatic), fn_ty)
217         }
218         ty::FnMutClosureKind => {
219             ccx.tcx().mk_mut_ref(ccx.tcx().mk_region(ty::ReStatic), fn_ty)
220         }
221         ty::FnOnceClosureKind => fn_ty,
222     }
223 }
224
225 pub fn kind_for_closure(ccx: &CrateContext, closure_id: DefId) -> ty::ClosureKind {
226     *ccx.tcx().tables.borrow().closure_kinds.get(&closure_id).unwrap()
227 }
228
229 pub fn get_extern_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
230                                   did: DefId,
231                                   t: Ty<'tcx>)
232                                   -> ValueRef {
233     let name = csearch::get_symbol(&ccx.sess().cstore, did);
234     let ty = type_of(ccx, t);
235     match ccx.externs().borrow_mut().get(&name) {
236         Some(n) => return *n,
237         None => (),
238     }
239     // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
240     // FIXME(nagisa): investigate whether it can be changed into define_global
241     let c = declare::declare_global(ccx, &name[..], ty);
242     // Thread-local statics in some other crate need to *always* be linked
243     // against in a thread-local fashion, so we need to be sure to apply the
244     // thread-local attribute locally if it was present remotely. If we
245     // don't do this then linker errors can be generated where the linker
246     // complains that one object files has a thread local version of the
247     // symbol and another one doesn't.
248     for attr in ccx.tcx().get_attrs(did).iter() {
249         if attr.check_name("thread_local") {
250             llvm::set_thread_local(c, true);
251         }
252     }
253     if ccx.use_dll_storage_attrs() {
254         llvm::SetDLLStorageClass(c, llvm::DLLImportStorageClass);
255     }
256     ccx.externs().borrow_mut().insert(name.to_string(), c);
257     return c;
258 }
259
260 fn require_alloc_fn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, info_ty: Ty<'tcx>, it: LangItem) -> DefId {
261     match bcx.tcx().lang_items.require(it) {
262         Ok(id) => id,
263         Err(s) => {
264             bcx.sess().fatal(&format!("allocation of `{}` {}", info_ty, s));
265         }
266     }
267 }
268
269 // The following malloc_raw_dyn* functions allocate a box to contain
270 // a given type, but with a potentially dynamic size.
271
272 pub fn malloc_raw_dyn<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
273                                   llty_ptr: Type,
274                                   info_ty: Ty<'tcx>,
275                                   size: ValueRef,
276                                   align: ValueRef,
277                                   debug_loc: DebugLoc)
278                                   -> Result<'blk, 'tcx> {
279     let _icx = push_ctxt("malloc_raw_exchange");
280
281     // Allocate space:
282     let r = callee::trans_lang_call(bcx,
283                                     require_alloc_fn(bcx, info_ty, ExchangeMallocFnLangItem),
284                                     &[size, align],
285                                     None,
286                                     debug_loc);
287
288     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
289 }
290
291
292 pub fn bin_op_to_icmp_predicate(ccx: &CrateContext,
293                                 op: hir::BinOp_,
294                                 signed: bool)
295                                 -> llvm::IntPredicate {
296     match op {
297         hir::BiEq => llvm::IntEQ,
298         hir::BiNe => llvm::IntNE,
299         hir::BiLt => if signed { llvm::IntSLT } else { llvm::IntULT },
300         hir::BiLe => if signed { llvm::IntSLE } else { llvm::IntULE },
301         hir::BiGt => if signed { llvm::IntSGT } else { llvm::IntUGT },
302         hir::BiGe => if signed { llvm::IntSGE } else { llvm::IntUGE },
303         op => {
304             ccx.sess()
305                .bug(&format!("comparison_op_to_icmp_predicate: expected comparison operator, \
306                               found {:?}",
307                              op));
308         }
309     }
310 }
311
312 pub fn bin_op_to_fcmp_predicate(ccx: &CrateContext, op: hir::BinOp_) -> llvm::RealPredicate {
313     match op {
314         hir::BiEq => llvm::RealOEQ,
315         hir::BiNe => llvm::RealUNE,
316         hir::BiLt => llvm::RealOLT,
317         hir::BiLe => llvm::RealOLE,
318         hir::BiGt => llvm::RealOGT,
319         hir::BiGe => llvm::RealOGE,
320         op => {
321             ccx.sess()
322                .bug(&format!("comparison_op_to_fcmp_predicate: expected comparison operator, \
323                               found {:?}",
324                              op));
325         }
326     }
327 }
328
329 pub fn compare_fat_ptrs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
330                                     lhs_addr: ValueRef,
331                                     lhs_extra: ValueRef,
332                                     rhs_addr: ValueRef,
333                                     rhs_extra: ValueRef,
334                                     _t: Ty<'tcx>,
335                                     op: hir::BinOp_,
336                                     debug_loc: DebugLoc)
337                                     -> ValueRef {
338     match op {
339         hir::BiEq => {
340             let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
341             let extra_eq = ICmp(bcx, llvm::IntEQ, lhs_extra, rhs_extra, debug_loc);
342             And(bcx, addr_eq, extra_eq, debug_loc)
343         }
344         hir::BiNe => {
345             let addr_eq = ICmp(bcx, llvm::IntNE, lhs_addr, rhs_addr, debug_loc);
346             let extra_eq = ICmp(bcx, llvm::IntNE, lhs_extra, rhs_extra, debug_loc);
347             Or(bcx, addr_eq, extra_eq, debug_loc)
348         }
349         hir::BiLe | hir::BiLt | hir::BiGe | hir::BiGt => {
350             // a OP b ~ a.0 STRICT(OP) b.0 | (a.0 == b.0 && a.1 OP a.1)
351             let (op, strict_op) = match op {
352                 hir::BiLt => (llvm::IntULT, llvm::IntULT),
353                 hir::BiLe => (llvm::IntULE, llvm::IntULT),
354                 hir::BiGt => (llvm::IntUGT, llvm::IntUGT),
355                 hir::BiGe => (llvm::IntUGE, llvm::IntUGT),
356                 _ => unreachable!(),
357             };
358
359             let addr_eq = ICmp(bcx, llvm::IntEQ, lhs_addr, rhs_addr, debug_loc);
360             let extra_op = ICmp(bcx, op, lhs_extra, rhs_extra, debug_loc);
361             let addr_eq_extra_op = And(bcx, addr_eq, extra_op, debug_loc);
362
363             let addr_strict = ICmp(bcx, strict_op, lhs_addr, rhs_addr, debug_loc);
364             Or(bcx, addr_strict, addr_eq_extra_op, debug_loc)
365         }
366         _ => {
367             bcx.tcx().sess.bug("unexpected fat ptr binop");
368         }
369     }
370 }
371
372 pub fn compare_scalar_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
373                                         lhs: ValueRef,
374                                         rhs: ValueRef,
375                                         t: Ty<'tcx>,
376                                         op: hir::BinOp_,
377                                         debug_loc: DebugLoc)
378                                         -> ValueRef {
379     match t.sty {
380         ty::TyTuple(ref tys) if tys.is_empty() => {
381             // We don't need to do actual comparisons for nil.
382             // () == () holds but () < () does not.
383             match op {
384                 hir::BiEq | hir::BiLe | hir::BiGe => return C_bool(bcx.ccx(), true),
385                 hir::BiNe | hir::BiLt | hir::BiGt => return C_bool(bcx.ccx(), false),
386                 // refinements would be nice
387                 _ => bcx.sess().bug("compare_scalar_types: must be a comparison operator"),
388             }
389         }
390         ty::TyBareFn(..) | ty::TyBool | ty::TyUint(_) | ty::TyChar => {
391             ICmp(bcx,
392                  bin_op_to_icmp_predicate(bcx.ccx(), op, false),
393                  lhs,
394                  rhs,
395                  debug_loc)
396         }
397         ty::TyRawPtr(mt) if common::type_is_sized(bcx.tcx(), mt.ty) => {
398             ICmp(bcx,
399                  bin_op_to_icmp_predicate(bcx.ccx(), op, false),
400                  lhs,
401                  rhs,
402                  debug_loc)
403         }
404         ty::TyRawPtr(_) => {
405             let lhs_addr = Load(bcx, GEPi(bcx, lhs, &[0, abi::FAT_PTR_ADDR]));
406             let lhs_extra = Load(bcx, GEPi(bcx, lhs, &[0, abi::FAT_PTR_EXTRA]));
407
408             let rhs_addr = Load(bcx, GEPi(bcx, rhs, &[0, abi::FAT_PTR_ADDR]));
409             let rhs_extra = Load(bcx, GEPi(bcx, rhs, &[0, abi::FAT_PTR_EXTRA]));
410             compare_fat_ptrs(bcx,
411                              lhs_addr,
412                              lhs_extra,
413                              rhs_addr,
414                              rhs_extra,
415                              t,
416                              op,
417                              debug_loc)
418         }
419         ty::TyInt(_) => {
420             ICmp(bcx,
421                  bin_op_to_icmp_predicate(bcx.ccx(), op, true),
422                  lhs,
423                  rhs,
424                  debug_loc)
425         }
426         ty::TyFloat(_) => {
427             FCmp(bcx,
428                  bin_op_to_fcmp_predicate(bcx.ccx(), op),
429                  lhs,
430                  rhs,
431                  debug_loc)
432         }
433         // Should never get here, because t is scalar.
434         _ => bcx.sess().bug("non-scalar type passed to compare_scalar_types"),
435     }
436 }
437
438 pub fn compare_simd_types<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
439                                       lhs: ValueRef,
440                                       rhs: ValueRef,
441                                       t: Ty<'tcx>,
442                                       ret_ty: Type,
443                                       op: hir::BinOp_,
444                                       debug_loc: DebugLoc)
445                                       -> ValueRef {
446     let signed = match t.sty {
447         ty::TyFloat(_) => {
448             let cmp = bin_op_to_fcmp_predicate(bcx.ccx(), op);
449             return SExt(bcx, FCmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty);
450         },
451         ty::TyUint(_) => false,
452         ty::TyInt(_) => true,
453         _ => bcx.sess().bug("compare_simd_types: invalid SIMD type"),
454     };
455
456     let cmp = bin_op_to_icmp_predicate(bcx.ccx(), op, signed);
457     // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
458     // to get the correctly sized type. This will compile to a single instruction
459     // once the IR is converted to assembly if the SIMD instruction is supported
460     // by the target architecture.
461     SExt(bcx, ICmp(bcx, cmp, lhs, rhs, debug_loc), ret_ty)
462 }
463
464 // Iterates through the elements of a structural type.
465 pub fn iter_structural_ty<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
466                                          av: ValueRef,
467                                          t: Ty<'tcx>,
468                                          mut f: F)
469                                          -> Block<'blk, 'tcx>
470     where F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>
471 {
472     let _icx = push_ctxt("iter_structural_ty");
473
474     fn iter_variant<'blk, 'tcx, F>(cx: Block<'blk, 'tcx>,
475                                    repr: &adt::Repr<'tcx>,
476                                    av: ValueRef,
477                                    variant: ty::VariantDef<'tcx>,
478                                    substs: &Substs<'tcx>,
479                                    f: &mut F)
480                                    -> Block<'blk, 'tcx>
481         where F: FnMut(Block<'blk, 'tcx>, ValueRef, Ty<'tcx>) -> Block<'blk, 'tcx>
482     {
483         let _icx = push_ctxt("iter_variant");
484         let tcx = cx.tcx();
485         let mut cx = cx;
486
487         for (i, field) in variant.fields.iter().enumerate() {
488             let arg = monomorphize::field_ty(tcx, substs, field);
489             cx = f(cx,
490                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
491                    arg);
492         }
493         return cx;
494     }
495
496     let (data_ptr, info) = if common::type_is_sized(cx.tcx(), t) {
497         (av, None)
498     } else {
499         let data = expr::get_dataptr(cx, av);
500         let info = expr::get_meta(cx, av);
501         (Load(cx, data), Some(Load(cx, info)))
502     };
503
504     let mut cx = cx;
505     match t.sty {
506         ty::TyStruct(..) => {
507             let repr = adt::represent_type(cx.ccx(), t);
508             let VariantInfo { fields, discr } = VariantInfo::from_ty(cx.tcx(), t, None);
509             for (i, &Field(_, field_ty)) in fields.iter().enumerate() {
510                 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, discr, i);
511
512                 let val = if common::type_is_sized(cx.tcx(), field_ty) {
513                     llfld_a
514                 } else {
515                     let scratch = datum::rvalue_scratch_datum(cx, field_ty, "__fat_ptr_iter");
516                     Store(cx, llfld_a, expr::get_dataptr(cx, scratch.val));
517                     Store(cx, info.unwrap(), expr::get_meta(cx, scratch.val));
518                     scratch.val
519                 };
520                 cx = f(cx, val, field_ty);
521             }
522         }
523         ty::TyClosure(_, ref substs) => {
524             let repr = adt::represent_type(cx.ccx(), t);
525             for (i, upvar_ty) in substs.upvar_tys.iter().enumerate() {
526                 let llupvar = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
527                 cx = f(cx, llupvar, upvar_ty);
528             }
529         }
530         ty::TyArray(_, n) => {
531             let (base, len) = tvec::get_fixed_base_and_len(cx, data_ptr, n);
532             let unit_ty = t.sequence_element_type(cx.tcx());
533             cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
534         }
535         ty::TySlice(_) | ty::TyStr => {
536             let unit_ty = t.sequence_element_type(cx.tcx());
537             cx = tvec::iter_vec_raw(cx, data_ptr, unit_ty, info.unwrap(), f);
538         }
539         ty::TyTuple(ref args) => {
540             let repr = adt::represent_type(cx.ccx(), t);
541             for (i, arg) in args.iter().enumerate() {
542                 let llfld_a = adt::trans_field_ptr(cx, &*repr, data_ptr, 0, i);
543                 cx = f(cx, llfld_a, *arg);
544             }
545         }
546         ty::TyEnum(en, substs) => {
547             let fcx = cx.fcx;
548             let ccx = fcx.ccx;
549
550             let repr = adt::represent_type(ccx, t);
551             let n_variants = en.variants.len();
552
553             // NB: we must hit the discriminant first so that structural
554             // comparison know not to proceed when the discriminants differ.
555
556             match adt::trans_switch(cx, &*repr, av) {
557                 (_match::Single, None) => {
558                     if n_variants != 0 {
559                         assert!(n_variants == 1);
560                         cx = iter_variant(cx, &*repr, av, &en.variants[0], substs, &mut f);
561                     }
562                 }
563                 (_match::Switch, Some(lldiscrim_a)) => {
564                     cx = f(cx, lldiscrim_a, cx.tcx().types.isize);
565
566                     // Create a fall-through basic block for the "else" case of
567                     // the switch instruction we're about to generate. Note that
568                     // we do **not** use an Unreachable instruction here, even
569                     // though most of the time this basic block will never be hit.
570                     //
571                     // When an enum is dropped it's contents are currently
572                     // overwritten to DTOR_DONE, which means the discriminant
573                     // could have changed value to something not within the actual
574                     // range of the discriminant. Currently this function is only
575                     // used for drop glue so in this case we just return quickly
576                     // from the outer function, and any other use case will only
577                     // call this for an already-valid enum in which case the `ret
578                     // void` will never be hit.
579                     let ret_void_cx = fcx.new_temp_block("enum-iter-ret-void");
580                     RetVoid(ret_void_cx, DebugLoc::None);
581                     let llswitch = Switch(cx, lldiscrim_a, ret_void_cx.llbb, n_variants);
582                     let next_cx = fcx.new_temp_block("enum-iter-next");
583
584                     for variant in &en.variants {
585                         let variant_cx = fcx.new_temp_block(&format!("enum-iter-variant-{}",
586                                                                      &variant.disr_val
587                                                                              .to_string()));
588                         let case_val = adt::trans_case(cx, &*repr, variant.disr_val);
589                         AddCase(llswitch, case_val, variant_cx.llbb);
590                         let variant_cx = iter_variant(variant_cx,
591                                                       &*repr,
592                                                       data_ptr,
593                                                       variant,
594                                                       substs,
595                                                       &mut f);
596                         Br(variant_cx, next_cx.llbb, DebugLoc::None);
597                     }
598                     cx = next_cx;
599                 }
600                 _ => ccx.sess().unimpl("value from adt::trans_switch in iter_structural_ty"),
601             }
602         }
603         _ => {
604             cx.sess().unimpl(&format!("type in iter_structural_ty: {}", t))
605         }
606     }
607     return cx;
608 }
609
610
611 /// Retrieve the information we are losing (making dynamic) in an unsizing
612 /// adjustment.
613 ///
614 /// The `old_info` argument is a bit funny. It is intended for use
615 /// in an upcast, where the new vtable for an object will be drived
616 /// from the old one.
617 pub fn unsized_info<'ccx, 'tcx>(ccx: &CrateContext<'ccx, 'tcx>,
618                                 source: Ty<'tcx>,
619                                 target: Ty<'tcx>,
620                                 old_info: Option<ValueRef>,
621                                 param_substs: &'tcx Substs<'tcx>)
622                                 -> ValueRef {
623     let (source, target) = ccx.tcx().struct_lockstep_tails(source, target);
624     match (&source.sty, &target.sty) {
625         (&ty::TyArray(_, len), &ty::TySlice(_)) => C_uint(ccx, len),
626         (&ty::TyTrait(_), &ty::TyTrait(_)) => {
627             // For now, upcasts are limited to changes in marker
628             // traits, and hence never actually require an actual
629             // change to the vtable.
630             old_info.expect("unsized_info: missing old info for trait upcast")
631         }
632         (_, &ty::TyTrait(box ty::TraitTy { ref principal, .. })) => {
633             // Note that we preserve binding levels here:
634             let substs = principal.0.substs.with_self_ty(source).erase_regions();
635             let substs = ccx.tcx().mk_substs(substs);
636             let trait_ref = ty::Binder(ty::TraitRef {
637                 def_id: principal.def_id(),
638                 substs: substs,
639             });
640             consts::ptrcast(meth::get_vtable(ccx, trait_ref, param_substs),
641                             Type::vtable_ptr(ccx))
642         }
643         _ => ccx.sess().bug(&format!("unsized_info: invalid unsizing {:?} -> {:?}",
644                                      source,
645                                      target)),
646     }
647 }
648
649 /// Coerce `src` to `dst_ty`. `src_ty` must be a thin pointer.
650 pub fn unsize_thin_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
651                                    src: ValueRef,
652                                    src_ty: Ty<'tcx>,
653                                    dst_ty: Ty<'tcx>)
654                                    -> (ValueRef, ValueRef) {
655     debug!("unsize_thin_ptr: {:?} => {:?}", src_ty, dst_ty);
656     match (&src_ty.sty, &dst_ty.sty) {
657         (&ty::TyBox(a), &ty::TyBox(b)) |
658         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
659          &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
660         (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
661          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
662         (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
663          &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
664             assert!(common::type_is_sized(bcx.tcx(), a));
665             let ptr_ty = type_of::in_memory_type_of(bcx.ccx(), b).ptr_to();
666             (PointerCast(bcx, src, ptr_ty),
667              unsized_info(bcx.ccx(), a, b, None, bcx.fcx.param_substs))
668         }
669         _ => bcx.sess().bug("unsize_thin_ptr: called on bad types"),
670     }
671 }
672
673 /// Coerce `src`, which is a reference to a value of type `src_ty`,
674 /// to a value of type `dst_ty` and store the result in `dst`
675 pub fn coerce_unsized_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
676                                        src: ValueRef,
677                                        src_ty: Ty<'tcx>,
678                                        dst: ValueRef,
679                                        dst_ty: Ty<'tcx>) {
680     match (&src_ty.sty, &dst_ty.sty) {
681         (&ty::TyBox(..), &ty::TyBox(..)) |
682         (&ty::TyRef(..), &ty::TyRef(..)) |
683         (&ty::TyRef(..), &ty::TyRawPtr(..)) |
684         (&ty::TyRawPtr(..), &ty::TyRawPtr(..)) => {
685             let (base, info) = if common::type_is_fat_ptr(bcx.tcx(), src_ty) {
686                 // fat-ptr to fat-ptr unsize preserves the vtable
687                 load_fat_ptr(bcx, src, src_ty)
688             } else {
689                 let base = load_ty(bcx, src, src_ty);
690                 unsize_thin_ptr(bcx, base, src_ty, dst_ty)
691             };
692             store_fat_ptr(bcx, base, info, dst, dst_ty);
693         }
694
695         // This can be extended to enums and tuples in the future.
696         // (&ty::TyEnum(def_id_a, _), &ty::TyEnum(def_id_b, _)) |
697         (&ty::TyStruct(def_a, _), &ty::TyStruct(def_b, _)) => {
698             assert_eq!(def_a, def_b);
699
700             let src_repr = adt::represent_type(bcx.ccx(), src_ty);
701             let src_fields = match &*src_repr {
702                 &adt::Repr::Univariant(ref s, _) => &s.fields,
703                 _ => bcx.sess().bug("struct has non-univariant repr"),
704             };
705             let dst_repr = adt::represent_type(bcx.ccx(), dst_ty);
706             let dst_fields = match &*dst_repr {
707                 &adt::Repr::Univariant(ref s, _) => &s.fields,
708                 _ => bcx.sess().bug("struct has non-univariant repr"),
709             };
710
711             let iter = src_fields.iter().zip(dst_fields).enumerate();
712             for (i, (src_fty, dst_fty)) in iter {
713                 if type_is_zero_size(bcx.ccx(), dst_fty) {
714                     continue;
715                 }
716
717                 let src_f = adt::trans_field_ptr(bcx, &src_repr, src, 0, i);
718                 let dst_f = adt::trans_field_ptr(bcx, &dst_repr, dst, 0, i);
719                 if src_fty == dst_fty {
720                     memcpy_ty(bcx, dst_f, src_f, src_fty);
721                 } else {
722                     coerce_unsized_into(bcx, src_f, src_fty, dst_f, dst_fty);
723                 }
724             }
725         }
726         _ => bcx.sess().bug(&format!("coerce_unsized_into: invalid coercion {:?} -> {:?}",
727                                      src_ty,
728                                      dst_ty)),
729     }
730 }
731
732 pub fn cast_shift_expr_rhs(cx: Block, op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
733     cast_shift_rhs(op, lhs, rhs, |a, b| Trunc(cx, a, b), |a, b| ZExt(cx, a, b))
734 }
735
736 pub fn cast_shift_const_rhs(op: hir::BinOp_, lhs: ValueRef, rhs: ValueRef) -> ValueRef {
737     cast_shift_rhs(op,
738                    lhs,
739                    rhs,
740                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
741                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
742 }
743
744 fn cast_shift_rhs<F, G>(op: hir::BinOp_,
745                         lhs: ValueRef,
746                         rhs: ValueRef,
747                         trunc: F,
748                         zext: G)
749                         -> ValueRef
750     where F: FnOnce(ValueRef, Type) -> ValueRef,
751           G: FnOnce(ValueRef, Type) -> ValueRef
752 {
753     // Shifts may have any size int on the rhs
754     if rustc_front::util::is_shift_binop(op) {
755         let mut rhs_llty = val_ty(rhs);
756         let mut lhs_llty = val_ty(lhs);
757         if rhs_llty.kind() == Vector {
758             rhs_llty = rhs_llty.element_type()
759         }
760         if lhs_llty.kind() == Vector {
761             lhs_llty = lhs_llty.element_type()
762         }
763         let rhs_sz = rhs_llty.int_width();
764         let lhs_sz = lhs_llty.int_width();
765         if lhs_sz < rhs_sz {
766             trunc(rhs, lhs_llty)
767         } else if lhs_sz > rhs_sz {
768             // FIXME (#1877: If shifting by negative
769             // values becomes not undefined then this is wrong.
770             zext(rhs, lhs_llty)
771         } else {
772             rhs
773         }
774     } else {
775         rhs
776     }
777 }
778
779 pub fn llty_and_min_for_signed_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
780                                               val_t: Ty<'tcx>)
781                                               -> (Type, u64) {
782     match val_t.sty {
783         ty::TyInt(t) => {
784             let llty = Type::int_from_ty(cx.ccx(), t);
785             let min = match t {
786                 ast::TyIs if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
787                 ast::TyIs => i64::MIN as u64,
788                 ast::TyI8 => i8::MIN as u64,
789                 ast::TyI16 => i16::MIN as u64,
790                 ast::TyI32 => i32::MIN as u64,
791                 ast::TyI64 => i64::MIN as u64,
792             };
793             (llty, min)
794         }
795         _ => unreachable!(),
796     }
797 }
798
799 pub fn fail_if_zero_or_overflows<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
800                                              call_info: NodeIdAndSpan,
801                                              divrem: hir::BinOp,
802                                              lhs: ValueRef,
803                                              rhs: ValueRef,
804                                              rhs_t: Ty<'tcx>)
805                                              -> Block<'blk, 'tcx> {
806     let (zero_text, overflow_text) = if divrem.node == hir::BiDiv {
807         ("attempted to divide by zero",
808          "attempted to divide with overflow")
809     } else {
810         ("attempted remainder with a divisor of zero",
811          "attempted remainder with overflow")
812     };
813     let debug_loc = call_info.debug_loc();
814
815     let (is_zero, is_signed) = match rhs_t.sty {
816         ty::TyInt(t) => {
817             let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0, false);
818             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), true)
819         }
820         ty::TyUint(t) => {
821             let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0, false);
822             (ICmp(cx, llvm::IntEQ, rhs, zero, debug_loc), false)
823         }
824         ty::TyStruct(def, _) if def.is_simd() => {
825             let mut res = C_bool(cx.ccx(), false);
826             for i in 0..rhs_t.simd_size(cx.tcx()) {
827                 res = Or(cx,
828                          res,
829                          IsNull(cx, ExtractElement(cx, rhs, C_int(cx.ccx(), i as i64))),
830                          debug_loc);
831             }
832             (res, false)
833         }
834         _ => {
835             cx.sess().bug(&format!("fail-if-zero on unexpected type: {}", rhs_t));
836         }
837     };
838     let bcx = with_cond(cx, is_zero, |bcx| {
839         controlflow::trans_fail(bcx, call_info, InternedString::new(zero_text))
840     });
841
842     // To quote LLVM's documentation for the sdiv instruction:
843     //
844     //      Division by zero leads to undefined behavior. Overflow also leads
845     //      to undefined behavior; this is a rare case, but can occur, for
846     //      example, by doing a 32-bit division of -2147483648 by -1.
847     //
848     // In order to avoid undefined behavior, we perform runtime checks for
849     // signed division/remainder which would trigger overflow. For unsigned
850     // integers, no action beyond checking for zero need be taken.
851     if is_signed {
852         let (llty, min) = llty_and_min_for_signed_ty(cx, rhs_t);
853         let minus_one = ICmp(bcx,
854                              llvm::IntEQ,
855                              rhs,
856                              C_integral(llty, !0, false),
857                              debug_loc);
858         with_cond(bcx, minus_one, |bcx| {
859             let is_min = ICmp(bcx,
860                               llvm::IntEQ,
861                               lhs,
862                               C_integral(llty, min, true),
863                               debug_loc);
864             with_cond(bcx, is_min, |bcx| {
865                 controlflow::trans_fail(bcx, call_info, InternedString::new(overflow_text))
866             })
867         })
868     } else {
869         bcx
870     }
871 }
872
873 pub fn trans_external_path<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
874                                      did: DefId,
875                                      t: Ty<'tcx>)
876                                      -> ValueRef {
877     let name = csearch::get_symbol(&ccx.sess().cstore, did);
878     match t.sty {
879         ty::TyBareFn(_, ref fn_ty) => {
880             match ccx.sess().target.target.adjust_abi(fn_ty.abi) {
881                 Rust | RustCall => {
882                     get_extern_rust_fn(ccx, t, &name[..], did)
883                 }
884                 RustIntrinsic | PlatformIntrinsic => {
885                     ccx.sess().bug("unexpected intrinsic in trans_external_path")
886                 }
887                 _ => {
888                     let attrs = csearch::get_item_attrs(&ccx.sess().cstore, did);
889                     foreign::register_foreign_item_fn(ccx, fn_ty.abi, t, &name, &attrs)
890                 }
891             }
892         }
893         _ => {
894             get_extern_const(ccx, did, t)
895         }
896     }
897 }
898
899 pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
900                           llfn: ValueRef,
901                           llargs: &[ValueRef],
902                           fn_ty: Ty<'tcx>,
903                           debug_loc: DebugLoc)
904                           -> (ValueRef, Block<'blk, 'tcx>) {
905     let _icx = push_ctxt("invoke_");
906     if bcx.unreachable.get() {
907         return (C_null(Type::i8(bcx.ccx())), bcx);
908     }
909
910     let attributes = attributes::from_fn_type(bcx.ccx(), fn_ty);
911
912     match bcx.opt_node_id {
913         None => {
914             debug!("invoke at ???");
915         }
916         Some(id) => {
917             debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
918         }
919     }
920
921     if need_invoke(bcx) {
922         debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
923         for &llarg in llargs {
924             debug!("arg: {}", bcx.val_to_string(llarg));
925         }
926         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
927         let landing_pad = bcx.fcx.get_landing_pad();
928
929         let llresult = Invoke(bcx,
930                               llfn,
931                               &llargs[..],
932                               normal_bcx.llbb,
933                               landing_pad,
934                               Some(attributes),
935                               debug_loc);
936         return (llresult, normal_bcx);
937     } else {
938         debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb);
939         for &llarg in llargs {
940             debug!("arg: {}", bcx.val_to_string(llarg));
941         }
942
943         let llresult = Call(bcx, llfn, &llargs[..], Some(attributes), debug_loc);
944         return (llresult, bcx);
945     }
946 }
947
948 /// Returns whether this session's target will use SEH-based unwinding.
949 ///
950 /// This is only true for MSVC targets, and even then the 64-bit MSVC target
951 /// currently uses SEH-ish unwinding with DWARF info tables to the side (same as
952 /// 64-bit MinGW) instead of "full SEH".
953 pub fn wants_msvc_seh(sess: &Session) -> bool {
954     sess.target.target.options.is_like_msvc && sess.target.target.arch == "x86"
955 }
956
957 pub fn need_invoke(bcx: Block) -> bool {
958     // FIXME(#25869) currently SEH-based unwinding is pretty buggy in LLVM and
959     //               is being overhauled as this is being written. Until that
960     //               time such that upstream LLVM's implementation is more solid
961     //               and we start binding it we need to skip invokes for any
962     //               target which wants SEH-based unwinding.
963     if bcx.sess().no_landing_pads() || wants_msvc_seh(bcx.sess()) {
964         return false;
965     }
966
967     // Avoid using invoke if we are already inside a landing pad.
968     if bcx.is_lpad {
969         return false;
970     }
971
972     bcx.fcx.needs_invoke()
973 }
974
975 pub fn load_if_immediate<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, t: Ty<'tcx>) -> ValueRef {
976     let _icx = push_ctxt("load_if_immediate");
977     if type_is_immediate(cx.ccx(), t) {
978         return load_ty(cx, v, t);
979     }
980     return v;
981 }
982
983 /// Helper for loading values from memory. Does the necessary conversion if the in-memory type
984 /// differs from the type used for SSA values. Also handles various special cases where the type
985 /// gives us better information about what we are loading.
986 pub fn load_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, ptr: ValueRef, t: Ty<'tcx>) -> ValueRef {
987     if cx.unreachable.get() || type_is_zero_size(cx.ccx(), t) {
988         return C_undef(type_of::type_of(cx.ccx(), t));
989     }
990
991     let ptr = to_arg_ty_ptr(cx, ptr, t);
992     let align = type_of::align_of(cx.ccx(), t);
993
994     if type_is_immediate(cx.ccx(), t) && type_of::type_of(cx.ccx(), t).is_aggregate() {
995         let load = Load(cx, ptr);
996         unsafe {
997             llvm::LLVMSetAlignment(load, align);
998         }
999         return load;
1000     }
1001
1002     unsafe {
1003         let global = llvm::LLVMIsAGlobalVariable(ptr);
1004         if !global.is_null() && llvm::LLVMIsGlobalConstant(global) == llvm::True {
1005             let val = llvm::LLVMGetInitializer(global);
1006             if !val.is_null() {
1007                 return to_arg_ty(cx, val, t);
1008             }
1009         }
1010     }
1011
1012     let val = if t.is_bool() {
1013         LoadRangeAssert(cx, ptr, 0, 2, llvm::False)
1014     } else if t.is_char() {
1015         // a char is a Unicode codepoint, and so takes values from 0
1016         // to 0x10FFFF inclusive only.
1017         LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
1018     } else if (t.is_region_ptr() || t.is_unique()) && !common::type_is_fat_ptr(cx.tcx(), t) {
1019         LoadNonNull(cx, ptr)
1020     } else {
1021         Load(cx, ptr)
1022     };
1023
1024     unsafe {
1025         llvm::LLVMSetAlignment(val, align);
1026     }
1027
1028     to_arg_ty(cx, val, t)
1029 }
1030
1031 /// Helper for storing values in memory. Does the necessary conversion if the in-memory type
1032 /// differs from the type used for SSA values.
1033 pub fn store_ty<'blk, 'tcx>(cx: Block<'blk, 'tcx>, v: ValueRef, dst: ValueRef, t: Ty<'tcx>) {
1034     if cx.unreachable.get() {
1035         return;
1036     }
1037
1038     debug!("store_ty: {} : {:?} <- {}",
1039            cx.val_to_string(dst),
1040            t,
1041            cx.val_to_string(v));
1042
1043     if common::type_is_fat_ptr(cx.tcx(), t) {
1044         Store(cx,
1045               ExtractValue(cx, v, abi::FAT_PTR_ADDR),
1046               expr::get_dataptr(cx, dst));
1047         Store(cx,
1048               ExtractValue(cx, v, abi::FAT_PTR_EXTRA),
1049               expr::get_meta(cx, dst));
1050     } else {
1051         let store = Store(cx, from_arg_ty(cx, v, t), to_arg_ty_ptr(cx, dst, t));
1052         unsafe {
1053             llvm::LLVMSetAlignment(store, type_of::align_of(cx.ccx(), t));
1054         }
1055     }
1056 }
1057
1058 pub fn store_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1059                                  data: ValueRef,
1060                                  extra: ValueRef,
1061                                  dst: ValueRef,
1062                                  _ty: Ty<'tcx>) {
1063     // FIXME: emit metadata
1064     Store(cx, data, expr::get_dataptr(cx, dst));
1065     Store(cx, extra, expr::get_meta(cx, dst));
1066 }
1067
1068 pub fn load_fat_ptr<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1069                                 src: ValueRef,
1070                                 _ty: Ty<'tcx>)
1071                                 -> (ValueRef, ValueRef) {
1072     // FIXME: emit metadata
1073     (Load(cx, expr::get_dataptr(cx, src)),
1074      Load(cx, expr::get_meta(cx, src)))
1075 }
1076
1077 pub fn from_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
1078     if ty.is_bool() {
1079         ZExt(bcx, val, Type::i8(bcx.ccx()))
1080     } else {
1081         val
1082     }
1083 }
1084
1085 pub fn to_arg_ty(bcx: Block, val: ValueRef, ty: Ty) -> ValueRef {
1086     if ty.is_bool() {
1087         Trunc(bcx, val, Type::i1(bcx.ccx()))
1088     } else {
1089         val
1090     }
1091 }
1092
1093 pub fn to_arg_ty_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ptr: ValueRef, ty: Ty<'tcx>) -> ValueRef {
1094     if type_is_immediate(bcx.ccx(), ty) && type_of::type_of(bcx.ccx(), ty).is_aggregate() {
1095         // We want to pass small aggregates as immediate values, but using an aggregate LLVM type
1096         // for this leads to bad optimizations, so its arg type is an appropriately sized integer
1097         // and we have to convert it
1098         BitCast(bcx, ptr, type_of::arg_type_of(bcx.ccx(), ty).ptr_to())
1099     } else {
1100         ptr
1101     }
1102 }
1103
1104 pub fn init_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, local: &hir::Local) -> Block<'blk, 'tcx> {
1105     debug!("init_local(bcx={}, local.id={})", bcx.to_str(), local.id);
1106     let _indenter = indenter();
1107     let _icx = push_ctxt("init_local");
1108     _match::store_local(bcx, local)
1109 }
1110
1111 pub fn raw_block<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1112                              is_lpad: bool,
1113                              llbb: BasicBlockRef)
1114                              -> Block<'blk, 'tcx> {
1115     common::BlockS::new(llbb, is_lpad, None, fcx)
1116 }
1117
1118 pub fn with_cond<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>, val: ValueRef, f: F) -> Block<'blk, 'tcx>
1119     where F: FnOnce(Block<'blk, 'tcx>) -> Block<'blk, 'tcx>
1120 {
1121     let _icx = push_ctxt("with_cond");
1122
1123     if bcx.unreachable.get() || common::const_to_opt_uint(val) == Some(0) {
1124         return bcx;
1125     }
1126
1127     let fcx = bcx.fcx;
1128     let next_cx = fcx.new_temp_block("next");
1129     let cond_cx = fcx.new_temp_block("cond");
1130     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb, DebugLoc::None);
1131     let after_cx = f(cond_cx);
1132     if !after_cx.terminated.get() {
1133         Br(after_cx, next_cx.llbb, DebugLoc::None);
1134     }
1135     next_cx
1136 }
1137
1138 pub fn call_lifetime_start(cx: Block, ptr: ValueRef) {
1139     if cx.sess().opts.optimize == config::No {
1140         return;
1141     }
1142
1143     let _icx = push_ctxt("lifetime_start");
1144     let ccx = cx.ccx();
1145
1146     let size = machine::llsize_of_alloc(ccx, val_ty(ptr).element_type());
1147     if size == 0 {
1148         return;
1149     }
1150
1151     let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1152     let lifetime_start = ccx.get_intrinsic(&"llvm.lifetime.start");
1153     Call(cx,
1154          lifetime_start,
1155          &[C_u64(ccx, size), ptr],
1156          None,
1157          DebugLoc::None);
1158 }
1159
1160 pub fn call_lifetime_end(cx: Block, ptr: ValueRef) {
1161     if cx.sess().opts.optimize == config::No {
1162         return;
1163     }
1164
1165     let _icx = push_ctxt("lifetime_end");
1166     let ccx = cx.ccx();
1167
1168     let size = machine::llsize_of_alloc(ccx, val_ty(ptr).element_type());
1169     if size == 0 {
1170         return;
1171     }
1172
1173     let ptr = PointerCast(cx, ptr, Type::i8p(ccx));
1174     let lifetime_end = ccx.get_intrinsic(&"llvm.lifetime.end");
1175     Call(cx,
1176          lifetime_end,
1177          &[C_u64(ccx, size), ptr],
1178          None,
1179          DebugLoc::None);
1180 }
1181
1182 // Generates code for resumption of unwind at the end of a landing pad.
1183 pub fn trans_unwind_resume(bcx: Block, lpval: ValueRef) {
1184     if !bcx.sess().target.target.options.custom_unwind_resume {
1185         Resume(bcx, lpval);
1186     } else {
1187         let exc_ptr = ExtractValue(bcx, lpval, 0);
1188         let llunwresume = bcx.fcx.eh_unwind_resume();
1189         Call(bcx, llunwresume, &[exc_ptr], None, DebugLoc::None);
1190         Unreachable(bcx);
1191     }
1192 }
1193
1194
1195 pub fn call_memcpy(cx: Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1196     let _icx = push_ctxt("call_memcpy");
1197     let ccx = cx.ccx();
1198     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
1199     let key = format!("llvm.memcpy.p0i8.p0i8.i{}", ptr_width);
1200     let memcpy = ccx.get_intrinsic(&key);
1201     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1202     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1203     let size = IntCast(cx, n_bytes, ccx.int_type());
1204     let align = C_i32(ccx, align as i32);
1205     let volatile = C_bool(ccx, false);
1206     Call(cx,
1207          memcpy,
1208          &[dst_ptr, src_ptr, size, align, volatile],
1209          None,
1210          DebugLoc::None);
1211 }
1212
1213 pub fn memcpy_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, dst: ValueRef, src: ValueRef, t: Ty<'tcx>) {
1214     let _icx = push_ctxt("memcpy_ty");
1215     let ccx = bcx.ccx();
1216
1217     if type_is_zero_size(ccx, t) {
1218         return;
1219     }
1220
1221     if t.is_structural() {
1222         let llty = type_of::type_of(ccx, t);
1223         let llsz = llsize_of(ccx, llty);
1224         let llalign = type_of::align_of(ccx, t);
1225         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1226     } else {
1227         store_ty(bcx, load_ty(bcx, src, t), dst, t);
1228     }
1229 }
1230
1231 pub fn drop_done_fill_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1232     if cx.unreachable.get() {
1233         return;
1234     }
1235     let _icx = push_ctxt("drop_done_fill_mem");
1236     let bcx = cx;
1237     memfill(&B(bcx), llptr, t, adt::DTOR_DONE);
1238 }
1239
1240 pub fn init_zero_mem<'blk, 'tcx>(cx: Block<'blk, 'tcx>, llptr: ValueRef, t: Ty<'tcx>) {
1241     if cx.unreachable.get() {
1242         return;
1243     }
1244     let _icx = push_ctxt("init_zero_mem");
1245     let bcx = cx;
1246     memfill(&B(bcx), llptr, t, 0);
1247 }
1248
1249 // Always use this function instead of storing a constant byte to the memory
1250 // in question. e.g. if you store a zero constant, LLVM will drown in vreg
1251 // allocation for large data structures, and the generated code will be
1252 // awful. (A telltale sign of this is large quantities of
1253 // `mov [byte ptr foo],0` in the generated code.)
1254 fn memfill<'a, 'tcx>(b: &Builder<'a, 'tcx>, llptr: ValueRef, ty: Ty<'tcx>, byte: u8) {
1255     let _icx = push_ctxt("memfill");
1256     let ccx = b.ccx;
1257
1258     let llty = type_of::type_of(ccx, ty);
1259     let ptr_width = &ccx.sess().target.target.target_pointer_width[..];
1260     let intrinsic_key = format!("llvm.memset.p0i8.i{}", ptr_width);
1261
1262     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1263     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1264     let llzeroval = C_u8(ccx, byte);
1265     let size = machine::llsize_of(ccx, llty);
1266     let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
1267     let volatile = C_bool(ccx, false);
1268     b.call(llintrinsicfn,
1269            &[llptr, llzeroval, size, align, volatile],
1270            None);
1271 }
1272
1273 pub fn alloc_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, t: Ty<'tcx>, name: &str) -> ValueRef {
1274     let _icx = push_ctxt("alloc_ty");
1275     let ccx = bcx.ccx();
1276     let ty = type_of::type_of(ccx, t);
1277     assert!(!t.has_param_types());
1278     alloca(bcx, ty, name)
1279 }
1280
1281 pub fn alloca(cx: Block, ty: Type, name: &str) -> ValueRef {
1282     let _icx = push_ctxt("alloca");
1283     if cx.unreachable.get() {
1284         unsafe {
1285             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1286         }
1287     }
1288     debuginfo::clear_source_location(cx.fcx);
1289     Alloca(cx, ty, name)
1290 }
1291
1292 pub fn set_value_name(val: ValueRef, name: &str) {
1293     unsafe {
1294         let name = CString::new(name).unwrap();
1295         llvm::LLVMSetValueName(val, name.as_ptr());
1296     }
1297 }
1298
1299 // Creates the alloca slot which holds the pointer to the slot for the final return value
1300 pub fn make_return_slot_pointer<'a, 'tcx>(fcx: &FunctionContext<'a, 'tcx>,
1301                                           output_type: Ty<'tcx>)
1302                                           -> ValueRef {
1303     let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1304
1305     // We create an alloca to hold a pointer of type `output_type`
1306     // which will hold the pointer to the right alloca which has the
1307     // final ret value
1308     if fcx.needs_ret_allocas {
1309         // Let's create the stack slot
1310         let slot = AllocaFcx(fcx, lloutputtype.ptr_to(), "llretslotptr");
1311
1312         // and if we're using an out pointer, then store that in our newly made slot
1313         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1314             let outptr = get_param(fcx.llfn, 0);
1315
1316             let b = fcx.ccx.builder();
1317             b.position_before(fcx.alloca_insert_pt.get().unwrap());
1318             b.store(outptr, slot);
1319         }
1320
1321         slot
1322
1323     // But if there are no nested returns, we skip the indirection and have a single
1324     // retslot
1325     } else {
1326         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1327             get_param(fcx.llfn, 0)
1328         } else {
1329             AllocaFcx(fcx, lloutputtype, "sret_slot")
1330         }
1331     }
1332 }
1333
1334 struct FindNestedReturn {
1335     found: bool,
1336 }
1337
1338 impl FindNestedReturn {
1339     fn new() -> FindNestedReturn {
1340         FindNestedReturn {
1341             found: false,
1342         }
1343     }
1344 }
1345
1346 impl<'v> Visitor<'v> for FindNestedReturn {
1347     fn visit_expr(&mut self, e: &hir::Expr) {
1348         match e.node {
1349             hir::ExprRet(..) => {
1350                 self.found = true;
1351             }
1352             _ => intravisit::walk_expr(self, e),
1353         }
1354     }
1355 }
1356
1357 fn build_cfg(tcx: &ty::ctxt, id: ast::NodeId) -> (ast::NodeId, Option<cfg::CFG>) {
1358     let blk = match tcx.map.find(id) {
1359         Some(hir_map::NodeItem(i)) => {
1360             match i.node {
1361                 hir::ItemFn(_, _, _, _, _, ref blk) => {
1362                     blk
1363                 }
1364                 _ => tcx.sess.bug("unexpected item variant in has_nested_returns"),
1365             }
1366         }
1367         Some(hir_map::NodeTraitItem(trait_item)) => {
1368             match trait_item.node {
1369                 hir::MethodTraitItem(_, Some(ref body)) => body,
1370                 _ => {
1371                     tcx.sess.bug("unexpected variant: trait item other than a provided method in \
1372                                   has_nested_returns")
1373                 }
1374             }
1375         }
1376         Some(hir_map::NodeImplItem(impl_item)) => {
1377             match impl_item.node {
1378                 hir::ImplItemKind::Method(_, ref body) => body,
1379                 _ => {
1380                     tcx.sess.bug("unexpected variant: non-method impl item in has_nested_returns")
1381                 }
1382             }
1383         }
1384         Some(hir_map::NodeExpr(e)) => {
1385             match e.node {
1386                 hir::ExprClosure(_, _, ref blk) => blk,
1387                 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns"),
1388             }
1389         }
1390         Some(hir_map::NodeVariant(..)) |
1391         Some(hir_map::NodeStructCtor(..)) => return (ast::DUMMY_NODE_ID, None),
1392
1393         // glue, shims, etc
1394         None if id == ast::DUMMY_NODE_ID => return (ast::DUMMY_NODE_ID, None),
1395
1396         _ => tcx.sess.bug(&format!("unexpected variant in has_nested_returns: {}",
1397                                    tcx.map.path_to_string(id))),
1398     };
1399
1400     (blk.id, Some(cfg::CFG::new(tcx, blk)))
1401 }
1402
1403 // Checks for the presence of "nested returns" in a function.
1404 // Nested returns are when the inner expression of a return expression
1405 // (the 'expr' in 'return expr') contains a return expression. Only cases
1406 // where the outer return is actually reachable are considered. Implicit
1407 // returns from the end of blocks are considered as well.
1408 //
1409 // This check is needed to handle the case where the inner expression is
1410 // part of a larger expression that may have already partially-filled the
1411 // return slot alloca. This can cause errors related to clean-up due to
1412 // the clobbering of the existing value in the return slot.
1413 fn has_nested_returns(tcx: &ty::ctxt, cfg: &cfg::CFG, blk_id: ast::NodeId) -> bool {
1414     for index in cfg.graph.depth_traverse(cfg.entry) {
1415         let n = cfg.graph.node_data(index);
1416         match tcx.map.find(n.id()) {
1417             Some(hir_map::NodeExpr(ex)) => {
1418                 if let hir::ExprRet(Some(ref ret_expr)) = ex.node {
1419                     let mut visitor = FindNestedReturn::new();
1420                     intravisit::walk_expr(&mut visitor, &**ret_expr);
1421                     if visitor.found {
1422                         return true;
1423                     }
1424                 }
1425             }
1426             Some(hir_map::NodeBlock(blk)) if blk.id == blk_id => {
1427                 let mut visitor = FindNestedReturn::new();
1428                 walk_list!(&mut visitor, visit_expr, &blk.expr);
1429                 if visitor.found {
1430                     return true;
1431                 }
1432             }
1433             _ => {}
1434         }
1435     }
1436
1437     return false;
1438 }
1439
1440 // NB: must keep 4 fns in sync:
1441 //
1442 //  - type_of_fn
1443 //  - create_datums_for_fn_args.
1444 //  - new_fn_ctxt
1445 //  - trans_args
1446 //
1447 // Be warned! You must call `init_function` before doing anything with the
1448 // returned function context.
1449 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1450                              llfndecl: ValueRef,
1451                              id: ast::NodeId,
1452                              has_env: bool,
1453                              output_type: ty::FnOutput<'tcx>,
1454                              param_substs: &'tcx Substs<'tcx>,
1455                              sp: Option<Span>,
1456                              block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1457                              -> FunctionContext<'a, 'tcx> {
1458     common::validate_substs(param_substs);
1459
1460     debug!("new_fn_ctxt(path={}, id={}, param_substs={:?})",
1461            if id == !0 {
1462                "".to_string()
1463            } else {
1464                ccx.tcx().map.path_to_string(id).to_string()
1465            },
1466            id,
1467            param_substs);
1468
1469     let uses_outptr = match output_type {
1470         ty::FnConverging(output_type) => {
1471             let substd_output_type = monomorphize::apply_param_substs(ccx.tcx(),
1472                                                                       param_substs,
1473                                                                       &output_type);
1474             type_of::return_uses_outptr(ccx, substd_output_type)
1475         }
1476         ty::FnDiverging => false,
1477     };
1478     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1479     let (blk_id, cfg) = build_cfg(ccx.tcx(), id);
1480     let nested_returns = if let Some(ref cfg) = cfg {
1481         has_nested_returns(ccx.tcx(), cfg, blk_id)
1482     } else {
1483         false
1484     };
1485
1486     let mir = ccx.mir_map().get(&id);
1487
1488     let mut fcx = FunctionContext {
1489         mir: mir,
1490         llfn: llfndecl,
1491         llenv: None,
1492         llretslotptr: Cell::new(None),
1493         param_env: ccx.tcx().empty_parameter_environment(),
1494         alloca_insert_pt: Cell::new(None),
1495         llreturn: Cell::new(None),
1496         needs_ret_allocas: nested_returns,
1497         personality: Cell::new(None),
1498         caller_expects_out_pointer: uses_outptr,
1499         lllocals: RefCell::new(NodeMap()),
1500         llupvars: RefCell::new(NodeMap()),
1501         lldropflag_hints: RefCell::new(DropFlagHintsMap::new()),
1502         id: id,
1503         param_substs: param_substs,
1504         span: sp,
1505         block_arena: block_arena,
1506         ccx: ccx,
1507         debug_context: debug_context,
1508         scopes: RefCell::new(Vec::new()),
1509         cfg: cfg,
1510     };
1511
1512     if has_env {
1513         fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1514     }
1515
1516     fcx
1517 }
1518
1519 /// Performs setup on a newly created function, creating the entry scope block
1520 /// and allocating space for the return pointer.
1521 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1522                                skip_retptr: bool,
1523                                output: ty::FnOutput<'tcx>)
1524                                -> Block<'a, 'tcx> {
1525     let entry_bcx = fcx.new_temp_block("entry-block");
1526
1527     // Use a dummy instruction as the insertion point for all allocas.
1528     // This is later removed in FunctionContext::cleanup.
1529     fcx.alloca_insert_pt.set(Some(unsafe {
1530         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1531         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1532     }));
1533
1534     if let ty::FnConverging(output_type) = output {
1535         // This shouldn't need to recompute the return type,
1536         // as new_fn_ctxt did it already.
1537         let substd_output_type = fcx.monomorphize(&output_type);
1538         if !return_type_is_void(fcx.ccx, substd_output_type) {
1539             // If the function returns nil/bot, there is no real return
1540             // value, so do not set `llretslotptr`.
1541             if !skip_retptr || fcx.caller_expects_out_pointer {
1542                 // Otherwise, we normally allocate the llretslotptr, unless we
1543                 // have been instructed to skip it for immediate return
1544                 // values.
1545                 fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1546             }
1547         }
1548     }
1549
1550     // Create the drop-flag hints for every unfragmented path in the function.
1551     let tcx = fcx.ccx.tcx();
1552     let fn_did = tcx.map.local_def_id(fcx.id);
1553     let mut hints = fcx.lldropflag_hints.borrow_mut();
1554     let fragment_infos = tcx.fragment_infos.borrow();
1555
1556     // Intern table for drop-flag hint datums.
1557     let mut seen = HashMap::new();
1558
1559     if let Some(fragment_infos) = fragment_infos.get(&fn_did) {
1560         for &info in fragment_infos {
1561
1562             let make_datum = |id| {
1563                 let init_val = C_u8(fcx.ccx, adt::DTOR_NEEDED_HINT);
1564                 let llname = &format!("dropflag_hint_{}", id);
1565                 debug!("adding hint {}", llname);
1566                 let ty = tcx.types.u8;
1567                 let ptr = alloc_ty(entry_bcx, ty, llname);
1568                 Store(entry_bcx, init_val, ptr);
1569                 let flag = datum::Lvalue::new_dropflag_hint("base::init_function");
1570                 datum::Datum::new(ptr, ty, flag)
1571             };
1572
1573             let (var, datum) = match info {
1574                 ty::FragmentInfo::Moved { var, .. } |
1575                 ty::FragmentInfo::Assigned { var, .. } => {
1576                     let datum = seen.get(&var).cloned().unwrap_or_else(|| {
1577                         let datum = make_datum(var);
1578                         seen.insert(var, datum.clone());
1579                         datum
1580                     });
1581                     (var, datum)
1582                 }
1583             };
1584             match info {
1585                 ty::FragmentInfo::Moved { move_expr: expr_id, .. } => {
1586                     debug!("FragmentInfo::Moved insert drop hint for {}", expr_id);
1587                     hints.insert(expr_id, DropHint::new(var, datum));
1588                 }
1589                 ty::FragmentInfo::Assigned { assignee_id: expr_id, .. } => {
1590                     debug!("FragmentInfo::Assigned insert drop hint for {}", expr_id);
1591                     hints.insert(expr_id, DropHint::new(var, datum));
1592                 }
1593             }
1594         }
1595     }
1596
1597     entry_bcx
1598 }
1599
1600 // NB: must keep 4 fns in sync:
1601 //
1602 //  - type_of_fn
1603 //  - create_datums_for_fn_args.
1604 //  - new_fn_ctxt
1605 //  - trans_args
1606
1607 pub fn arg_kind<'a, 'tcx>(cx: &FunctionContext<'a, 'tcx>, t: Ty<'tcx>) -> datum::Rvalue {
1608     use trans::datum::{ByRef, ByValue};
1609
1610     datum::Rvalue {
1611         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1612     }
1613 }
1614
1615 // create_datums_for_fn_args: creates lvalue datums for each of the
1616 // incoming function arguments.
1617 pub fn create_datums_for_fn_args<'a, 'tcx>(mut bcx: Block<'a, 'tcx>,
1618                                            args: &[hir::Arg],
1619                                            arg_tys: &[Ty<'tcx>],
1620                                            has_tupled_arg: bool,
1621                                            arg_scope: cleanup::CustomScopeIndex)
1622                                            -> Block<'a, 'tcx> {
1623     let _icx = push_ctxt("create_datums_for_fn_args");
1624     let fcx = bcx.fcx;
1625     let arg_scope_id = cleanup::CustomScope(arg_scope);
1626
1627     // Return an array wrapping the ValueRefs that we get from `get_param` for
1628     // each argument into datums.
1629     //
1630     // For certain mode/type combinations, the raw llarg values are passed
1631     // by value.  However, within the fn body itself, we want to always
1632     // have all locals and arguments be by-ref so that we can cancel the
1633     // cleanup and for better interaction with LLVM's debug info.  So, if
1634     // the argument would be passed by value, we store it into an alloca.
1635     // This alloca should be optimized away by LLVM's mem-to-reg pass in
1636     // the event it's not truly needed.
1637     let mut idx = fcx.arg_offset() as c_uint;
1638     for (i, &arg_ty) in arg_tys.iter().enumerate() {
1639         let arg_datum = if !has_tupled_arg || i < arg_tys.len() - 1 {
1640             if type_of::arg_is_indirect(bcx.ccx(), arg_ty) &&
1641                bcx.sess().opts.debuginfo != FullDebugInfo {
1642                 // Don't copy an indirect argument to an alloca, the caller
1643                 // already put it in a temporary alloca and gave it up, unless
1644                 // we emit extra-debug-info, which requires local allocas :(.
1645                 let llarg = get_param(fcx.llfn, idx);
1646                 idx += 1;
1647                 bcx.fcx.schedule_lifetime_end(arg_scope_id, llarg);
1648                 bcx.fcx.schedule_drop_mem(arg_scope_id, llarg, arg_ty, None);
1649
1650                 datum::Datum::new(llarg,
1651                                   arg_ty,
1652                                   datum::Lvalue::new("create_datum_for_fn_args"))
1653             } else if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
1654                 let data = get_param(fcx.llfn, idx);
1655                 let extra = get_param(fcx.llfn, idx + 1);
1656                 idx += 2;
1657                 unpack_datum!(bcx, datum::lvalue_scratch_datum(bcx, arg_ty, "",
1658                                                         arg_scope_id, (data, extra),
1659                                                         |(data, extra), bcx, dst| {
1660                     Store(bcx, data, expr::get_dataptr(bcx, dst));
1661                     Store(bcx, extra, expr::get_meta(bcx, dst));
1662                     bcx
1663                 }))
1664             } else {
1665                 let llarg = get_param(fcx.llfn, idx);
1666                 idx += 1;
1667                 let tmp = datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty));
1668                 unpack_datum!(bcx,
1669                               datum::lvalue_scratch_datum(bcx,
1670                                                           arg_ty,
1671                                                           "",
1672                                                           arg_scope_id,
1673                                                           tmp,
1674                                                           |tmp, bcx, dst| tmp.store_to(bcx, dst)))
1675             }
1676         } else {
1677             // FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1678             match arg_ty.sty {
1679                 ty::TyTuple(ref tupled_arg_tys) => {
1680                     unpack_datum!(bcx,
1681                                   datum::lvalue_scratch_datum(bcx,
1682                                                               arg_ty,
1683                                                               "tupled_args",
1684                                                               arg_scope_id,
1685                                                               (),
1686                                                               |(),
1687                                                                mut bcx,
1688                                                                llval| {
1689                         for (j, &tupled_arg_ty) in
1690                                     tupled_arg_tys.iter().enumerate() {
1691                             let lldest = StructGEP(bcx, llval, j);
1692                             if common::type_is_fat_ptr(bcx.tcx(), tupled_arg_ty) {
1693                                 let data = get_param(bcx.fcx.llfn, idx);
1694                                 let extra = get_param(bcx.fcx.llfn, idx + 1);
1695                                 Store(bcx, data, expr::get_dataptr(bcx, lldest));
1696                                 Store(bcx, extra, expr::get_meta(bcx, lldest));
1697                                 idx += 2;
1698                             } else {
1699                                 let datum = datum::Datum::new(
1700                                     get_param(bcx.fcx.llfn, idx),
1701                                     tupled_arg_ty,
1702                                     arg_kind(bcx.fcx, tupled_arg_ty));
1703                                 idx += 1;
1704                                 bcx = datum.store_to(bcx, lldest);
1705                             };
1706                         }
1707                         bcx
1708                     }))
1709                 }
1710                 _ => {
1711                     bcx.tcx()
1712                        .sess
1713                        .bug("last argument of a function with `rust-call` ABI isn't a tuple?!")
1714                 }
1715             }
1716         };
1717
1718         let pat = &*args[i].pat;
1719         bcx = if let Some(name) = simple_name(pat) {
1720             // Generate nicer LLVM for the common case of fn a pattern
1721             // like `x: T`
1722             set_value_name(arg_datum.val, &bcx.name(name));
1723             bcx.fcx.lllocals.borrow_mut().insert(pat.id, arg_datum);
1724             bcx
1725         } else {
1726             // General path. Copy out the values that are used in the
1727             // pattern.
1728             _match::bind_irrefutable_pat(bcx, pat, arg_datum.match_input(), arg_scope_id)
1729         };
1730         debuginfo::create_argument_metadata(bcx, &args[i]);
1731     }
1732
1733     bcx
1734 }
1735
1736 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1737 // and builds the return block.
1738 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1739                              last_bcx: Block<'blk, 'tcx>,
1740                              retty: ty::FnOutput<'tcx>,
1741                              ret_debug_loc: DebugLoc) {
1742     let _icx = push_ctxt("finish_fn");
1743
1744     let ret_cx = match fcx.llreturn.get() {
1745         Some(llreturn) => {
1746             if !last_bcx.terminated.get() {
1747                 Br(last_bcx, llreturn, DebugLoc::None);
1748             }
1749             raw_block(fcx, false, llreturn)
1750         }
1751         None => last_bcx,
1752     };
1753
1754     // This shouldn't need to recompute the return type,
1755     // as new_fn_ctxt did it already.
1756     let substd_retty = fcx.monomorphize(&retty);
1757     build_return_block(fcx, ret_cx, substd_retty, ret_debug_loc);
1758
1759     debuginfo::clear_source_location(fcx);
1760     fcx.cleanup();
1761 }
1762
1763 // Builds the return block for a function.
1764 pub fn build_return_block<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1765                                       ret_cx: Block<'blk, 'tcx>,
1766                                       retty: ty::FnOutput<'tcx>,
1767                                       ret_debug_location: DebugLoc) {
1768     if fcx.llretslotptr.get().is_none() ||
1769        (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1770         return RetVoid(ret_cx, ret_debug_location);
1771     }
1772
1773     let retslot = if fcx.needs_ret_allocas {
1774         Load(ret_cx, fcx.llretslotptr.get().unwrap())
1775     } else {
1776         fcx.llretslotptr.get().unwrap()
1777     };
1778     let retptr = Value(retslot);
1779     match retptr.get_dominating_store(ret_cx) {
1780         // If there's only a single store to the ret slot, we can directly return
1781         // the value that was stored and omit the store and the alloca
1782         Some(s) => {
1783             let retval = s.get_operand(0).unwrap().get();
1784             s.erase_from_parent();
1785
1786             if retptr.has_no_uses() {
1787                 retptr.erase_from_parent();
1788             }
1789
1790             let retval = if retty == ty::FnConverging(fcx.ccx.tcx().types.bool) {
1791                 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1792             } else {
1793                 retval
1794             };
1795
1796             if fcx.caller_expects_out_pointer {
1797                 if let ty::FnConverging(retty) = retty {
1798                     store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1799                 }
1800                 RetVoid(ret_cx, ret_debug_location)
1801             } else {
1802                 Ret(ret_cx, retval, ret_debug_location)
1803             }
1804         }
1805         // Otherwise, copy the return value to the ret slot
1806         None => match retty {
1807             ty::FnConverging(retty) => {
1808                 if fcx.caller_expects_out_pointer {
1809                     memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1810                     RetVoid(ret_cx, ret_debug_location)
1811                 } else {
1812                     Ret(ret_cx, load_ty(ret_cx, retslot, retty), ret_debug_location)
1813                 }
1814             }
1815             ty::FnDiverging => {
1816                 if fcx.caller_expects_out_pointer {
1817                     RetVoid(ret_cx, ret_debug_location)
1818                 } else {
1819                     Ret(ret_cx, C_undef(Type::nil(fcx.ccx)), ret_debug_location)
1820                 }
1821             }
1822         },
1823     }
1824 }
1825
1826 /// Builds an LLVM function out of a source function.
1827 ///
1828 /// If the function closes over its environment a closure will be returned.
1829 pub fn trans_closure<'a, 'b, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1830                                    decl: &hir::FnDecl,
1831                                    body: &hir::Block,
1832                                    llfndecl: ValueRef,
1833                                    param_substs: &'tcx Substs<'tcx>,
1834                                    fn_ast_id: ast::NodeId,
1835                                    attributes: &[ast::Attribute],
1836                                    output_type: ty::FnOutput<'tcx>,
1837                                    abi: Abi,
1838                                    closure_env: closure::ClosureEnv<'b>) {
1839     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1840
1841     let _icx = push_ctxt("trans_closure");
1842     attributes::emit_uwtable(llfndecl, true);
1843
1844     debug!("trans_closure(..., param_substs={:?})", param_substs);
1845
1846     let has_env = match closure_env {
1847         closure::ClosureEnv::Closure(..) => true,
1848         closure::ClosureEnv::NotClosure => false,
1849     };
1850
1851     let (arena, fcx): (TypedArena<_>, FunctionContext);
1852     arena = TypedArena::new();
1853     fcx = new_fn_ctxt(ccx,
1854                       llfndecl,
1855                       fn_ast_id,
1856                       has_env,
1857                       output_type,
1858                       param_substs,
1859                       Some(body.span),
1860                       &arena);
1861     let mut bcx = init_function(&fcx, false, output_type);
1862
1863     if attributes.iter().any(|item| item.check_name("rustc_mir")) {
1864         mir::trans_mir(bcx);
1865         fcx.cleanup();
1866         return;
1867     }
1868
1869     // cleanup scope for the incoming arguments
1870     let fn_cleanup_debug_loc = debuginfo::get_cleanup_debug_loc_for_ast_node(ccx,
1871                                                                              fn_ast_id,
1872                                                                              body.span,
1873                                                                              true);
1874     let arg_scope = fcx.push_custom_cleanup_scope_with_debug_loc(fn_cleanup_debug_loc);
1875
1876     let block_ty = node_id_type(bcx, body.id);
1877
1878     // Set up arguments to the function.
1879     let monomorphized_arg_types = decl.inputs
1880                                       .iter()
1881                                       .map(|arg| node_id_type(bcx, arg.id))
1882                                       .collect::<Vec<_>>();
1883     for monomorphized_arg_type in &monomorphized_arg_types {
1884         debug!("trans_closure: monomorphized_arg_type: {:?}",
1885                monomorphized_arg_type);
1886     }
1887     debug!("trans_closure: function lltype: {}",
1888            bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1889
1890     let has_tupled_arg = match closure_env {
1891         closure::ClosureEnv::NotClosure => abi == RustCall,
1892         _ => false,
1893     };
1894
1895     bcx = create_datums_for_fn_args(bcx,
1896                                     &decl.inputs,
1897                                     &monomorphized_arg_types,
1898                                     has_tupled_arg,
1899                                     arg_scope);
1900
1901     bcx = closure_env.load(bcx, cleanup::CustomScope(arg_scope));
1902
1903     // Up until here, IR instructions for this function have explicitly not been annotated with
1904     // source code location, so we don't step into call setup code. From here on, source location
1905     // emitting should be enabled.
1906     debuginfo::start_emitting_source_locations(&fcx);
1907
1908     let dest = match fcx.llretslotptr.get() {
1909         Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, ty::FnConverging(block_ty), "iret_slot")),
1910         None => {
1911             assert!(type_is_zero_size(bcx.ccx(), block_ty));
1912             expr::Ignore
1913         }
1914     };
1915
1916     // This call to trans_block is the place where we bridge between
1917     // translation calls that don't have a return value (trans_crate,
1918     // trans_mod, trans_item, et cetera) and those that do
1919     // (trans_block, trans_expr, et cetera).
1920     bcx = controlflow::trans_block(bcx, body, dest);
1921
1922     match dest {
1923         expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1924             Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1925         }
1926         _ => {}
1927     }
1928
1929     match fcx.llreturn.get() {
1930         Some(_) => {
1931             Br(bcx, fcx.return_exit_block(), DebugLoc::None);
1932             fcx.pop_custom_cleanup_scope(arg_scope);
1933         }
1934         None => {
1935             // Microoptimization writ large: avoid creating a separate
1936             // llreturn basic block
1937             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1938         }
1939     };
1940
1941     // Put return block after all other blocks.
1942     // This somewhat improves single-stepping experience in debugger.
1943     unsafe {
1944         let llreturn = fcx.llreturn.get();
1945         if let Some(llreturn) = llreturn {
1946             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1947         }
1948     }
1949
1950     let ret_debug_loc = DebugLoc::At(fn_cleanup_debug_loc.id, fn_cleanup_debug_loc.span);
1951
1952     // Insert the mandatory first few basic blocks before lltop.
1953     finish_fn(&fcx, bcx, output_type, ret_debug_loc);
1954 }
1955
1956 /// Creates an LLVM function corresponding to a source language function.
1957 pub fn trans_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1958                           decl: &hir::FnDecl,
1959                           body: &hir::Block,
1960                           llfndecl: ValueRef,
1961                           param_substs: &'tcx Substs<'tcx>,
1962                           id: ast::NodeId,
1963                           attrs: &[ast::Attribute]) {
1964     let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1965     debug!("trans_fn(param_substs={:?})", param_substs);
1966     let _icx = push_ctxt("trans_fn");
1967     let fn_ty = ccx.tcx().node_id_to_type(id);
1968     let fn_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &fn_ty);
1969     let sig = fn_ty.fn_sig();
1970     let sig = ccx.tcx().erase_late_bound_regions(&sig);
1971     let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
1972     let output_type = sig.output;
1973     let abi = fn_ty.fn_abi();
1974     trans_closure(ccx,
1975                   decl,
1976                   body,
1977                   llfndecl,
1978                   param_substs,
1979                   id,
1980                   attrs,
1981                   output_type,
1982                   abi,
1983                   closure::ClosureEnv::NotClosure);
1984 }
1985
1986 pub fn trans_enum_variant<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1987                                     ctor_id: ast::NodeId,
1988                                     disr: ty::Disr,
1989                                     param_substs: &'tcx Substs<'tcx>,
1990                                     llfndecl: ValueRef) {
1991     let _icx = push_ctxt("trans_enum_variant");
1992
1993     trans_enum_variant_or_tuple_like_struct(ccx, ctor_id, disr, param_substs, llfndecl);
1994 }
1995
1996 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1997                                                  ctor_ty: Ty<'tcx>,
1998                                                  disr: ty::Disr,
1999                                                  args: callee::CallArgs,
2000                                                  dest: expr::Dest,
2001                                                  debug_loc: DebugLoc)
2002                                                  -> Result<'blk, 'tcx> {
2003
2004     let ccx = bcx.fcx.ccx;
2005
2006     let sig = ccx.tcx().erase_late_bound_regions(&ctor_ty.fn_sig());
2007     let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
2008     let result_ty = sig.output.unwrap();
2009
2010     // Get location to store the result. If the user does not care about
2011     // the result, just make a stack slot
2012     let llresult = match dest {
2013         expr::SaveIn(d) => d,
2014         expr::Ignore => {
2015             if !type_is_zero_size(ccx, result_ty) {
2016                 let llresult = alloc_ty(bcx, result_ty, "constructor_result");
2017                 call_lifetime_start(bcx, llresult);
2018                 llresult
2019             } else {
2020                 C_undef(type_of::type_of(ccx, result_ty).ptr_to())
2021             }
2022         }
2023     };
2024
2025     if !type_is_zero_size(ccx, result_ty) {
2026         match args {
2027             callee::ArgExprs(exprs) => {
2028                 let fields = exprs.iter().map(|x| &**x).enumerate().collect::<Vec<_>>();
2029                 bcx = expr::trans_adt(bcx,
2030                                       result_ty,
2031                                       disr,
2032                                       &fields[..],
2033                                       None,
2034                                       expr::SaveIn(llresult),
2035                                       debug_loc);
2036             }
2037             _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor"),
2038         }
2039     } else {
2040         // Just eval all the expressions (if any). Since expressions in Rust can have arbitrary
2041         // contents, there could be side-effects we need from them.
2042         match args {
2043             callee::ArgExprs(exprs) => {
2044                 for expr in exprs {
2045                     bcx = expr::trans_into(bcx, expr, expr::Ignore);
2046                 }
2047             }
2048             _ => (),
2049         }
2050     }
2051
2052     // If the caller doesn't care about the result
2053     // drop the temporary we made
2054     let bcx = match dest {
2055         expr::SaveIn(_) => bcx,
2056         expr::Ignore => {
2057             let bcx = glue::drop_ty(bcx, llresult, result_ty, debug_loc);
2058             if !type_is_zero_size(ccx, result_ty) {
2059                 call_lifetime_end(bcx, llresult);
2060             }
2061             bcx
2062         }
2063     };
2064
2065     Result::new(bcx, llresult)
2066 }
2067
2068 pub fn trans_tuple_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2069                                     ctor_id: ast::NodeId,
2070                                     param_substs: &'tcx Substs<'tcx>,
2071                                     llfndecl: ValueRef) {
2072     let _icx = push_ctxt("trans_tuple_struct");
2073
2074     trans_enum_variant_or_tuple_like_struct(ccx, ctor_id, 0, param_substs, llfndecl);
2075 }
2076
2077 fn trans_enum_variant_or_tuple_like_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2078                                                      ctor_id: ast::NodeId,
2079                                                      disr: ty::Disr,
2080                                                      param_substs: &'tcx Substs<'tcx>,
2081                                                      llfndecl: ValueRef) {
2082     let ctor_ty = ccx.tcx().node_id_to_type(ctor_id);
2083     let ctor_ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &ctor_ty);
2084
2085     let sig = ccx.tcx().erase_late_bound_regions(&ctor_ty.fn_sig());
2086     let sig = infer::normalize_associated_type(ccx.tcx(), &sig);
2087     let arg_tys = sig.inputs;
2088     let result_ty = sig.output;
2089
2090     let (arena, fcx): (TypedArena<_>, FunctionContext);
2091     arena = TypedArena::new();
2092     fcx = new_fn_ctxt(ccx,
2093                       llfndecl,
2094                       ctor_id,
2095                       false,
2096                       result_ty,
2097                       param_substs,
2098                       None,
2099                       &arena);
2100     let bcx = init_function(&fcx, false, result_ty);
2101
2102     assert!(!fcx.needs_ret_allocas);
2103
2104     if !type_is_zero_size(fcx.ccx, result_ty.unwrap()) {
2105         let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
2106         let repr = adt::represent_type(ccx, result_ty.unwrap());
2107         let mut llarg_idx = fcx.arg_offset() as c_uint;
2108         for (i, arg_ty) in arg_tys.into_iter().enumerate() {
2109             let lldestptr = adt::trans_field_ptr(bcx, &*repr, dest, disr, i);
2110             if common::type_is_fat_ptr(bcx.tcx(), arg_ty) {
2111                 Store(bcx,
2112                       get_param(fcx.llfn, llarg_idx),
2113                       expr::get_dataptr(bcx, lldestptr));
2114                 Store(bcx,
2115                       get_param(fcx.llfn, llarg_idx + 1),
2116                       expr::get_meta(bcx, lldestptr));
2117                 llarg_idx += 2;
2118             } else {
2119                 let arg = get_param(fcx.llfn, llarg_idx);
2120                 llarg_idx += 1;
2121
2122                 if arg_is_indirect(ccx, arg_ty) {
2123                     memcpy_ty(bcx, lldestptr, arg, arg_ty);
2124                 } else {
2125                     store_ty(bcx, arg, lldestptr, arg_ty);
2126                 }
2127             }
2128         }
2129         adt::trans_set_discr(bcx, &*repr, dest, disr);
2130     }
2131
2132     finish_fn(&fcx, bcx, result_ty, DebugLoc::None);
2133 }
2134
2135 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &hir::EnumDef, sp: Span, id: ast::NodeId) {
2136     let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
2137
2138     let print_info = ccx.sess().print_enum_sizes();
2139
2140     let levels = ccx.tcx().node_lint_levels.borrow();
2141     let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCES);
2142     let lvlsrc = levels.get(&(id, lint_id));
2143     let is_allow = lvlsrc.map_or(true, |&(lvl, _)| lvl == lint::Allow);
2144
2145     if is_allow && !print_info {
2146         // we're not interested in anything here
2147         return;
2148     }
2149
2150     let ty = ccx.tcx().node_id_to_type(id);
2151     let avar = adt::represent_type(ccx, ty);
2152     match *avar {
2153         adt::General(_, ref variants, _) => {
2154             for var in variants {
2155                 let mut size = 0;
2156                 for field in var.fields.iter().skip(1) {
2157                     // skip the discriminant
2158                     size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
2159                 }
2160                 sizes.push(size);
2161             }
2162         },
2163         _ => { /* its size is either constant or unimportant */ }
2164     }
2165
2166     let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
2167         |(l, s, li), (idx, &size)|
2168             if size > l {
2169                 (size, l, idx)
2170             } else if size > s {
2171                 (l, size, li)
2172             } else {
2173                 (l, s, li)
2174             }
2175     );
2176
2177     if print_info {
2178         let llty = type_of::sizing_type_of(ccx, ty);
2179
2180         let sess = &ccx.tcx().sess;
2181         sess.span_note(sp, &*format!("total size: {} bytes", llsize_of_real(ccx, llty)));
2182         match *avar {
2183             adt::General(..) => {
2184                 for (i, var) in enum_def.variants.iter().enumerate() {
2185                     ccx.tcx()
2186                        .sess
2187                        .span_note(var.span, &*format!("variant data: {} bytes", sizes[i]));
2188                 }
2189             }
2190             _ => {}
2191         }
2192     }
2193
2194     // we only warn if the largest variant is at least thrice as large as
2195     // the second-largest.
2196     if !is_allow && largest > slargest * 3 && slargest > 0 {
2197         // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
2198         // pass for the latter already ran.
2199         lint::raw_emit_lint(&ccx.tcx().sess,
2200                             lint::builtin::VARIANT_SIZE_DIFFERENCES,
2201                             *lvlsrc.unwrap(),
2202                             Some(sp),
2203                             &format!("enum variant is more than three times larger ({} bytes) \
2204                                       than the next largest (ignoring padding)",
2205                                      largest));
2206
2207         ccx.sess().span_note(enum_def.variants[largest_index].span,
2208                              "this variant is the largest");
2209     }
2210 }
2211
2212 pub fn llvm_linkage_by_name(name: &str) -> Option<Linkage> {
2213     // Use the names from src/llvm/docs/LangRef.rst here. Most types are only
2214     // applicable to variable declarations and may not really make sense for
2215     // Rust code in the first place but whitelist them anyway and trust that
2216     // the user knows what s/he's doing. Who knows, unanticipated use cases
2217     // may pop up in the future.
2218     //
2219     // ghost, dllimport, dllexport and linkonce_odr_autohide are not supported
2220     // and don't have to be, LLVM treats them as no-ops.
2221     match name {
2222         "appending" => Some(llvm::AppendingLinkage),
2223         "available_externally" => Some(llvm::AvailableExternallyLinkage),
2224         "common" => Some(llvm::CommonLinkage),
2225         "extern_weak" => Some(llvm::ExternalWeakLinkage),
2226         "external" => Some(llvm::ExternalLinkage),
2227         "internal" => Some(llvm::InternalLinkage),
2228         "linkonce" => Some(llvm::LinkOnceAnyLinkage),
2229         "linkonce_odr" => Some(llvm::LinkOnceODRLinkage),
2230         "private" => Some(llvm::PrivateLinkage),
2231         "weak" => Some(llvm::WeakAnyLinkage),
2232         "weak_odr" => Some(llvm::WeakODRLinkage),
2233         _ => None,
2234     }
2235 }
2236
2237
2238 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
2239 #[derive(Copy, Clone)]
2240 pub enum ValueOrigin {
2241     /// The LLVM `Value` is in this context because the corresponding item was
2242     /// assigned to the current compilation unit.
2243     OriginalTranslation,
2244     /// The `Value`'s corresponding item was assigned to some other compilation
2245     /// unit, but the `Value` was translated in this context anyway because the
2246     /// item is marked `#[inline]`.
2247     InlinedCopy,
2248 }
2249
2250 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
2251 /// If the `llval` is the direct translation of a specific Rust item, `id`
2252 /// should be set to the `NodeId` of that item.  (This mapping should be
2253 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
2254 /// `None`.)  `llval_origin` indicates whether `llval` is the translation of an
2255 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
2256 /// assigned to a different compilation unit.
2257 pub fn update_linkage(ccx: &CrateContext,
2258                       llval: ValueRef,
2259                       id: Option<ast::NodeId>,
2260                       llval_origin: ValueOrigin) {
2261     match llval_origin {
2262         InlinedCopy => {
2263             // `llval` is a translation of an item defined in a separate
2264             // compilation unit.  This only makes sense if there are at least
2265             // two compilation units.
2266             assert!(ccx.sess().opts.cg.codegen_units > 1);
2267             // `llval` is a copy of something defined elsewhere, so use
2268             // `AvailableExternallyLinkage` to avoid duplicating code in the
2269             // output.
2270             llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
2271             return;
2272         },
2273         OriginalTranslation => {},
2274     }
2275
2276     if let Some(id) = id {
2277         let item = ccx.tcx().map.get(id);
2278         if let hir_map::NodeItem(i) = item {
2279             if let Some(name) = attr::first_attr_value_str_by_name(&i.attrs, "linkage") {
2280                 if let Some(linkage) = llvm_linkage_by_name(&name) {
2281                     llvm::SetLinkage(llval, linkage);
2282                 } else {
2283                     ccx.sess().span_fatal(i.span, "invalid linkage specified");
2284                 }
2285                 return;
2286             }
2287         }
2288     }
2289
2290     match id {
2291         Some(id) if ccx.reachable().contains(&id) => {
2292             llvm::SetLinkage(llval, llvm::ExternalLinkage);
2293         },
2294         _ => {
2295             // `id` does not refer to an item in `ccx.reachable`.
2296             if ccx.sess().opts.cg.codegen_units > 1 {
2297                 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2298             } else {
2299                 llvm::SetLinkage(llval, llvm::InternalLinkage);
2300             }
2301         },
2302     }
2303 }
2304
2305 fn set_global_section(ccx: &CrateContext, llval: ValueRef, i: &hir::Item) {
2306     match attr::first_attr_value_str_by_name(&i.attrs, "link_section") {
2307         Some(sect) => {
2308             if contains_null(&sect) {
2309                 ccx.sess().fatal(&format!("Illegal null byte in link_section value: `{}`", &sect));
2310             }
2311             unsafe {
2312                 let buf = CString::new(sect.as_bytes()).unwrap();
2313                 llvm::LLVMSetSection(llval, buf.as_ptr());
2314             }
2315         },
2316         None => ()
2317     }
2318 }
2319
2320 pub fn trans_item(ccx: &CrateContext, item: &hir::Item) {
2321     let _icx = push_ctxt("trans_item");
2322
2323     let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2324
2325     match item.node {
2326         hir::ItemFn(ref decl, _, _, abi, ref generics, ref body) => {
2327             if !generics.is_type_parameterized() {
2328                 let trans_everywhere = attr::requests_inline(&item.attrs);
2329                 // Ignore `trans_everywhere` for cross-crate inlined items
2330                 // (`from_external`).  `trans_item` will be called once for each
2331                 // compilation unit that references the item, so it will still get
2332                 // translated everywhere it's needed.
2333                 for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2334                     let llfn = get_item_val(ccx, item.id);
2335                     let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
2336                     if abi != Rust {
2337                         foreign::trans_rust_fn_with_foreign_abi(ccx,
2338                                                                 &**decl,
2339                                                                 &**body,
2340                                                                 &item.attrs,
2341                                                                 llfn,
2342                                                                 empty_substs,
2343                                                                 item.id,
2344                                                                 None);
2345                     } else {
2346                         trans_fn(ccx,
2347                                  &**decl,
2348                                  &**body,
2349                                  llfn,
2350                                  empty_substs,
2351                                  item.id,
2352                                  &item.attrs);
2353                     }
2354                     set_global_section(ccx, llfn, item);
2355                     update_linkage(ccx,
2356                                    llfn,
2357                                    Some(item.id),
2358                                    if is_origin {
2359                                        OriginalTranslation
2360                                    } else {
2361                                        InlinedCopy
2362                                    });
2363
2364                     if is_entry_fn(ccx.sess(), item.id) {
2365                         create_entry_wrapper(ccx, item.span, llfn);
2366                         // check for the #[rustc_error] annotation, which forces an
2367                         // error in trans. This is used to write compile-fail tests
2368                         // that actually test that compilation succeeds without
2369                         // reporting an error.
2370                         let item_def_id = ccx.tcx().map.local_def_id(item.id);
2371                         if ccx.tcx().has_attr(item_def_id, "rustc_error") {
2372                             ccx.tcx().sess.span_fatal(item.span, "compilation successful");
2373                         }
2374                     }
2375                 }
2376             }
2377         }
2378         hir::ItemImpl(_, _, ref generics, _, _, ref impl_items) => {
2379             meth::trans_impl(ccx, item.name, &impl_items[..], generics, item.id);
2380         }
2381         hir::ItemMod(_) => {
2382             // modules have no equivalent at runtime, they just affect
2383             // the mangled names of things contained within
2384         }
2385         hir::ItemEnum(ref enum_definition, ref gens) => {
2386             if gens.ty_params.is_empty() {
2387                 // sizes only make sense for non-generic types
2388
2389                 enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2390             }
2391         }
2392         hir::ItemConst(..) => {}
2393         hir::ItemStatic(_, m, ref expr) => {
2394             let g = match consts::trans_static(ccx, m, expr, item.id, &item.attrs) {
2395                 Ok(g) => g,
2396                 Err(err) => ccx.tcx().sess.span_fatal(expr.span, &err.description()),
2397             };
2398             set_global_section(ccx, g, item);
2399             update_linkage(ccx, g, Some(item.id), OriginalTranslation);
2400         }
2401         hir::ItemForeignMod(ref foreign_mod) => {
2402             foreign::trans_foreign_mod(ccx, foreign_mod);
2403         }
2404         hir::ItemTrait(..) => {}
2405         _ => {
2406             // fall through
2407         }
2408     }
2409 }
2410
2411 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2412 pub fn register_fn_llvmty(ccx: &CrateContext,
2413                           sp: Span,
2414                           sym: String,
2415                           node_id: ast::NodeId,
2416                           cc: llvm::CallConv,
2417                           llfty: Type)
2418                           -> ValueRef {
2419     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2420
2421     let llfn = declare::define_fn(ccx, &sym[..], cc, llfty,
2422                                    ty::FnConverging(ccx.tcx().mk_nil())).unwrap_or_else(||{
2423         ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2424     });
2425     finish_register_fn(ccx, sym, node_id);
2426     llfn
2427 }
2428
2429 fn finish_register_fn(ccx: &CrateContext, sym: String, node_id: ast::NodeId) {
2430     ccx.item_symbols().borrow_mut().insert(node_id, sym);
2431 }
2432
2433 fn register_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2434                          sp: Span,
2435                          sym: String,
2436                          node_id: ast::NodeId,
2437                          node_type: Ty<'tcx>)
2438                          -> ValueRef {
2439     if let ty::TyBareFn(_, ref f) = node_type.sty {
2440         if f.abi != Rust && f.abi != RustCall {
2441             ccx.sess().span_bug(sp,
2442                                 &format!("only the `{}` or `{}` calling conventions are valid \
2443                                           for this function; `{}` was specified",
2444                                          Rust.name(),
2445                                          RustCall.name(),
2446                                          f.abi.name()));
2447         }
2448     } else {
2449         ccx.sess().span_bug(sp, "expected bare rust function")
2450     }
2451
2452     let llfn = declare::define_rust_fn(ccx, &sym[..], node_type).unwrap_or_else(|| {
2453         ccx.sess().span_fatal(sp, &format!("symbol `{}` is already defined", sym));
2454     });
2455     finish_register_fn(ccx, sym, node_id);
2456     llfn
2457 }
2458
2459 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2460     match *sess.entry_fn.borrow() {
2461         Some((entry_id, _)) => node_id == entry_id,
2462         None => false,
2463     }
2464 }
2465
2466 /// Create the `main` function which will initialise the rust runtime and call users’ main
2467 /// function.
2468 pub fn create_entry_wrapper(ccx: &CrateContext, sp: Span, main_llfn: ValueRef) {
2469     let et = ccx.sess().entry_type.get().unwrap();
2470     match et {
2471         config::EntryMain => {
2472             create_entry_fn(ccx, sp, main_llfn, true);
2473         }
2474         config::EntryStart => create_entry_fn(ccx, sp, main_llfn, false),
2475         config::EntryNone => {}    // Do nothing.
2476     }
2477
2478     fn create_entry_fn(ccx: &CrateContext,
2479                        sp: Span,
2480                        rust_main: ValueRef,
2481                        use_start_lang_item: bool) {
2482         let llfty = Type::func(&[ccx.int_type(), Type::i8p(ccx).ptr_to()], &ccx.int_type());
2483
2484         let llfn = declare::define_cfn(ccx, "main", llfty, ccx.tcx().mk_nil()).unwrap_or_else(|| {
2485             ccx.sess().span_err(sp, "entry symbol `main` defined multiple times");
2486             // FIXME: We should be smart and show a better diagnostic here.
2487             ccx.sess().help("did you use #[no_mangle] on `fn main`? Use #[start] instead");
2488             ccx.sess().abort_if_errors();
2489             panic!();
2490         });
2491
2492         let llbb = unsafe {
2493             llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, "top\0".as_ptr() as *const _)
2494         };
2495         let bld = ccx.raw_builder();
2496         unsafe {
2497             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2498
2499             debuginfo::gdb::insert_reference_to_gdb_debug_scripts_section_global(ccx);
2500
2501             let (start_fn, args) = if use_start_lang_item {
2502                 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2503                     Ok(id) => id,
2504                     Err(s) => {
2505                         ccx.sess().fatal(&s[..]);
2506                     }
2507                 };
2508                 let start_fn = if let Some(start_node_id) = ccx.tcx()
2509                                                                .map
2510                                                                .as_local_node_id(start_def_id) {
2511                     get_item_val(ccx, start_node_id)
2512                 } else {
2513                     let start_fn_type = csearch::get_type(ccx.tcx(), start_def_id).ty;
2514                     trans_external_path(ccx, start_def_id, start_fn_type)
2515                 };
2516
2517                 let args = {
2518                     let opaque_rust_main =
2519                         llvm::LLVMBuildPointerCast(bld,
2520                                                    rust_main,
2521                                                    Type::i8p(ccx).to_ref(),
2522                                                    "rust_main\0".as_ptr() as *const _);
2523
2524                     vec![opaque_rust_main, get_param(llfn, 0), get_param(llfn, 1)]
2525                 };
2526                 (start_fn, args)
2527             } else {
2528                 debug!("using user-defined start fn");
2529                 let args = vec![get_param(llfn, 0 as c_uint), get_param(llfn, 1 as c_uint)];
2530
2531                 (rust_main, args)
2532             };
2533
2534             let result = llvm::LLVMBuildCall(bld,
2535                                              start_fn,
2536                                              args.as_ptr(),
2537                                              args.len() as c_uint,
2538                                              noname());
2539
2540             llvm::LLVMBuildRet(bld, result);
2541         }
2542     }
2543 }
2544
2545 fn exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
2546                            id: ast::NodeId,
2547                            ty: Ty<'tcx>,
2548                            attrs: &[ast::Attribute])
2549                            -> String {
2550     match ccx.external_srcs().borrow().get(&id) {
2551         Some(&did) => {
2552             let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2553             debug!("found item {} in other crate...", sym);
2554             return sym;
2555         }
2556         None => {}
2557     }
2558
2559     match attr::find_export_name_attr(ccx.sess().diagnostic(), attrs) {
2560         // Use provided name
2561         Some(name) => name.to_string(),
2562         _ => {
2563             let path = ccx.tcx().map.def_path_from_id(id);
2564             if attr::contains_name(attrs, "no_mangle") {
2565                 // Don't mangle
2566                 path.last().unwrap().data.to_string()
2567             } else {
2568                 match weak_lang_items::link_name(attrs) {
2569                     Some(name) => name.to_string(),
2570                     None => {
2571                         // Usual name mangling
2572                         mangle_exported_name(ccx, path, ty, id)
2573                     }
2574                 }
2575             }
2576         }
2577     }
2578 }
2579
2580 fn contains_null(s: &str) -> bool {
2581     s.bytes().any(|b| b == 0)
2582 }
2583
2584 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2585     debug!("get_item_val(id=`{}`)", id);
2586
2587     match ccx.item_vals().borrow().get(&id).cloned() {
2588         Some(v) => return v,
2589         None => {}
2590     }
2591
2592     let item = ccx.tcx().map.get(id);
2593     debug!("get_item_val: id={} item={:?}", id, item);
2594     let val = match item {
2595         hir_map::NodeItem(i) => {
2596             let ty = ccx.tcx().node_id_to_type(i.id);
2597             let sym = || exported_name(ccx, id, ty, &i.attrs);
2598
2599             let v = match i.node {
2600                 hir::ItemStatic(..) => {
2601                     // If this static came from an external crate, then
2602                     // we need to get the symbol from csearch instead of
2603                     // using the current crate's name/version
2604                     // information in the hash of the symbol
2605                     let sym = sym();
2606                     debug!("making {}", sym);
2607
2608                     // Create the global before evaluating the initializer;
2609                     // this is necessary to allow recursive statics.
2610                     let llty = type_of(ccx, ty);
2611                     let g = declare::define_global(ccx, &sym[..], llty).unwrap_or_else(|| {
2612                         ccx.sess()
2613                            .span_fatal(i.span, &format!("symbol `{}` is already defined", sym))
2614                     });
2615
2616                     ccx.item_symbols().borrow_mut().insert(i.id, sym);
2617                     g
2618                 }
2619
2620                 hir::ItemFn(_, _, _, abi, _, _) => {
2621                     let sym = sym();
2622                     let llfn = if abi == Rust {
2623                         register_fn(ccx, i.span, sym, i.id, ty)
2624                     } else {
2625                         foreign::register_rust_fn_with_foreign_abi(ccx, i.span, sym, i.id)
2626                     };
2627                     attributes::from_fn_attrs(ccx, &i.attrs, llfn);
2628                     llfn
2629                 }
2630
2631                 _ => ccx.sess().bug("get_item_val: weird result in table"),
2632             };
2633
2634             v
2635         }
2636
2637         hir_map::NodeTraitItem(trait_item) => {
2638             debug!("get_item_val(): processing a NodeTraitItem");
2639             match trait_item.node {
2640                 hir::MethodTraitItem(_, Some(_)) => {
2641                     register_method(ccx, id, &trait_item.attrs, trait_item.span)
2642                 }
2643                 _ => {
2644                     ccx.sess().span_bug(trait_item.span,
2645                                         "unexpected variant: trait item other than a provided \
2646                                          method in get_item_val()");
2647                 }
2648             }
2649         }
2650
2651         hir_map::NodeImplItem(impl_item) => {
2652             match impl_item.node {
2653                 hir::ImplItemKind::Method(..) => {
2654                     register_method(ccx, id, &impl_item.attrs, impl_item.span)
2655                 }
2656                 _ => {
2657                     ccx.sess().span_bug(impl_item.span,
2658                                         "unexpected variant: non-method impl item in \
2659                                          get_item_val()");
2660                 }
2661             }
2662         }
2663
2664         hir_map::NodeForeignItem(ni) => {
2665             match ni.node {
2666                 hir::ForeignItemFn(..) => {
2667                     let abi = ccx.tcx().map.get_foreign_abi(id);
2668                     let ty = ccx.tcx().node_id_to_type(ni.id);
2669                     let name = foreign::link_name(&*ni);
2670                     foreign::register_foreign_item_fn(ccx, abi, ty, &name, &ni.attrs)
2671                 }
2672                 hir::ForeignItemStatic(..) => {
2673                     foreign::register_static(ccx, &*ni)
2674                 }
2675             }
2676         }
2677
2678         hir_map::NodeVariant(ref v) => {
2679             let llfn;
2680             let fields = if v.node.data.is_struct() {
2681                 ccx.sess().bug("struct variant kind unexpected in get_item_val")
2682             } else {
2683                 v.node.data.fields()
2684             };
2685             assert!(!fields.is_empty());
2686             let ty = ccx.tcx().node_id_to_type(id);
2687             let parent = ccx.tcx().map.get_parent(id);
2688             let enm = ccx.tcx().map.expect_item(parent);
2689             let sym = exported_name(ccx, id, ty, &enm.attrs);
2690
2691             llfn = match enm.node {
2692                 hir::ItemEnum(_, _) => {
2693                     register_fn(ccx, (*v).span, sym, id, ty)
2694                 }
2695                 _ => ccx.sess().bug("NodeVariant, shouldn't happen"),
2696             };
2697             attributes::inline(llfn, attributes::InlineAttr::Hint);
2698             llfn
2699         }
2700
2701         hir_map::NodeStructCtor(struct_def) => {
2702             // Only register the constructor if this is a tuple-like struct.
2703             let ctor_id = if struct_def.is_struct() {
2704                 ccx.sess().bug("attempt to register a constructor of a non-tuple-like struct")
2705             } else {
2706                 struct_def.id()
2707             };
2708             let parent = ccx.tcx().map.get_parent(id);
2709             let struct_item = ccx.tcx().map.expect_item(parent);
2710             let ty = ccx.tcx().node_id_to_type(ctor_id);
2711             let sym = exported_name(ccx, id, ty, &struct_item.attrs);
2712             let llfn = register_fn(ccx, struct_item.span, sym, ctor_id, ty);
2713             attributes::inline(llfn, attributes::InlineAttr::Hint);
2714             llfn
2715         }
2716
2717         ref variant => {
2718             ccx.sess().bug(&format!("get_item_val(): unexpected variant: {:?}", variant))
2719         }
2720     };
2721
2722     // All LLVM globals and functions are initially created as external-linkage
2723     // declarations.  If `trans_item`/`trans_fn` later turns the declaration
2724     // into a definition, it adjusts the linkage then (using `update_linkage`).
2725     //
2726     // The exception is foreign items, which have their linkage set inside the
2727     // call to `foreign::register_*` above.  We don't touch the linkage after
2728     // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2729     // other item translation functions do).
2730
2731     ccx.item_vals().borrow_mut().insert(id, val);
2732     val
2733 }
2734
2735 fn register_method(ccx: &CrateContext,
2736                    id: ast::NodeId,
2737                    attrs: &[ast::Attribute],
2738                    span: Span)
2739                    -> ValueRef {
2740     let mty = ccx.tcx().node_id_to_type(id);
2741
2742     let sym = exported_name(ccx, id, mty, &attrs);
2743
2744     if let ty::TyBareFn(_, ref f) = mty.sty {
2745         let llfn = if f.abi == Rust || f.abi == RustCall {
2746             register_fn(ccx, span, sym, id, mty)
2747         } else {
2748             foreign::register_rust_fn_with_foreign_abi(ccx, span, sym, id)
2749         };
2750         attributes::from_fn_attrs(ccx, &attrs, llfn);
2751         return llfn;
2752     } else {
2753         ccx.sess().span_bug(span, "expected bare rust function");
2754     }
2755 }
2756
2757 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'a, 'tcx>,
2758                                             ie: encoder::EncodeInlinedItem<'a>,
2759                                             reachable: &'a NodeSet)
2760                                             -> encoder::EncodeParams<'a, 'tcx> {
2761     encoder::EncodeParams {
2762         diag: cx.sess().diagnostic(),
2763         tcx: cx.tcx(),
2764         reexports: cx.export_map(),
2765         item_symbols: cx.item_symbols(),
2766         link_meta: cx.link_meta(),
2767         cstore: &cx.sess().cstore,
2768         encode_inlined_item: ie,
2769         reachable: reachable,
2770     }
2771 }
2772
2773 pub fn write_metadata(cx: &SharedCrateContext, krate: &hir::Crate, reachable: &NodeSet) -> Vec<u8> {
2774     use flate;
2775
2776     let any_library = cx.sess()
2777                         .crate_types
2778                         .borrow()
2779                         .iter()
2780                         .any(|ty| *ty != config::CrateTypeExecutable);
2781     if !any_library {
2782         return Vec::new();
2783     }
2784
2785     let encode_inlined_item: encoder::EncodeInlinedItem = Box::new(|ecx, rbml_w, ii| {
2786         astencode::encode_inlined_item(ecx, rbml_w, ii)
2787     });
2788
2789     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item, reachable);
2790     let metadata = encoder::encode_metadata(encode_parms, krate);
2791     let mut compressed = encoder::metadata_encoding_version.to_vec();
2792     compressed.push_all(&flate::deflate_bytes(&metadata));
2793     let llmeta = C_bytes_in_context(cx.metadata_llcx(), &compressed[..]);
2794     let llconst = C_struct_in_context(cx.metadata_llcx(), &[llmeta], false);
2795     let name = format!("rust_metadata_{}_{}",
2796                        cx.link_meta().crate_name,
2797                        cx.link_meta().crate_hash);
2798     let buf = CString::new(name).unwrap();
2799     let llglobal = unsafe {
2800         llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf.as_ptr())
2801     };
2802     unsafe {
2803         llvm::LLVMSetInitializer(llglobal, llconst);
2804         let name = loader::meta_section_name(&cx.sess().target.target);
2805         let name = CString::new(name).unwrap();
2806         llvm::LLVMSetSection(llglobal, name.as_ptr())
2807     }
2808     return metadata;
2809 }
2810
2811 /// Find any symbols that are defined in one compilation unit, but not declared
2812 /// in any other compilation unit.  Give these symbols internal linkage.
2813 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<&str>) {
2814     unsafe {
2815         let mut declared = HashSet::new();
2816
2817         // Collect all external declarations in all compilation units.
2818         for ccx in cx.iter() {
2819             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2820                 let linkage = llvm::LLVMGetLinkage(val);
2821                 // We only care about external declarations (not definitions)
2822                 // and available_externally definitions.
2823                 if !(linkage == llvm::ExternalLinkage as c_uint &&
2824                      llvm::LLVMIsDeclaration(val) != 0) &&
2825                    !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2826                     continue;
2827                 }
2828
2829                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2830                                .to_bytes()
2831                                .to_vec();
2832                 declared.insert(name);
2833             }
2834         }
2835
2836         // Examine each external definition.  If the definition is not used in
2837         // any other compilation unit, and is not reachable from other crates,
2838         // then give it internal linkage.
2839         for ccx in cx.iter() {
2840             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2841                 // We only care about external definitions.
2842                 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
2843                      llvm::LLVMIsDeclaration(val) == 0) {
2844                     continue;
2845                 }
2846
2847                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val))
2848                                .to_bytes()
2849                                .to_vec();
2850                 if !declared.contains(&name) &&
2851                    !reachable.contains(str::from_utf8(&name).unwrap()) {
2852                     llvm::SetLinkage(val, llvm::InternalLinkage);
2853                     llvm::SetDLLStorageClass(val, llvm::DefaultStorageClass);
2854                 }
2855             }
2856         }
2857     }
2858 }
2859
2860 // Create a `__imp_<symbol> = &symbol` global for every public static `symbol`.
2861 // This is required to satisfy `dllimport` references to static data in .rlibs
2862 // when using MSVC linker.  We do this only for data, as linker can fix up
2863 // code references on its own.
2864 // See #26591, #27438
2865 fn create_imps(cx: &SharedCrateContext) {
2866     // The x86 ABI seems to require that leading underscores are added to symbol
2867     // names, so we need an extra underscore on 32-bit. There's also a leading
2868     // '\x01' here which disables LLVM's symbol mangling (e.g. no extra
2869     // underscores added in front).
2870     let prefix = if cx.sess().target.target.target_pointer_width == "32" {
2871         "\x01__imp__"
2872     } else {
2873         "\x01__imp_"
2874     };
2875     unsafe {
2876         for ccx in cx.iter() {
2877             let exported: Vec<_> = iter_globals(ccx.llmod())
2878                                        .filter(|&val| {
2879                                            llvm::LLVMGetLinkage(val) ==
2880                                            llvm::ExternalLinkage as c_uint &&
2881                                            llvm::LLVMIsDeclaration(val) == 0
2882                                        })
2883                                        .collect();
2884
2885             let i8p_ty = Type::i8p(&ccx);
2886             for val in exported {
2887                 let name = CStr::from_ptr(llvm::LLVMGetValueName(val));
2888                 let mut imp_name = prefix.as_bytes().to_vec();
2889                 imp_name.extend(name.to_bytes());
2890                 let imp_name = CString::new(imp_name).unwrap();
2891                 let imp = llvm::LLVMAddGlobal(ccx.llmod(),
2892                                               i8p_ty.to_ref(),
2893                                               imp_name.as_ptr() as *const _);
2894                 let init = llvm::LLVMConstBitCast(val, i8p_ty.to_ref());
2895                 llvm::LLVMSetInitializer(imp, init);
2896                 llvm::SetLinkage(imp, llvm::ExternalLinkage);
2897             }
2898         }
2899     }
2900 }
2901
2902 struct ValueIter {
2903     cur: ValueRef,
2904     step: unsafe extern "C" fn(ValueRef) -> ValueRef,
2905 }
2906
2907 impl Iterator for ValueIter {
2908     type Item = ValueRef;
2909
2910     fn next(&mut self) -> Option<ValueRef> {
2911         let old = self.cur;
2912         if !old.is_null() {
2913             self.cur = unsafe { (self.step)(old) };
2914             Some(old)
2915         } else {
2916             None
2917         }
2918     }
2919 }
2920
2921 fn iter_globals(llmod: llvm::ModuleRef) -> ValueIter {
2922     unsafe {
2923         ValueIter {
2924             cur: llvm::LLVMGetFirstGlobal(llmod),
2925             step: llvm::LLVMGetNextGlobal,
2926         }
2927     }
2928 }
2929
2930 fn iter_functions(llmod: llvm::ModuleRef) -> ValueIter {
2931     unsafe {
2932         ValueIter {
2933             cur: llvm::LLVMGetFirstFunction(llmod),
2934             step: llvm::LLVMGetNextFunction,
2935         }
2936     }
2937 }
2938
2939 /// The context provided lists a set of reachable ids as calculated by
2940 /// middle::reachable, but this contains far more ids and symbols than we're
2941 /// actually exposing from the object file. This function will filter the set in
2942 /// the context to the set of ids which correspond to symbols that are exposed
2943 /// from the object file being generated.
2944 ///
2945 /// This list is later used by linkers to determine the set of symbols needed to
2946 /// be exposed from a dynamic library and it's also encoded into the metadata.
2947 pub fn filter_reachable_ids(ccx: &SharedCrateContext) -> NodeSet {
2948     ccx.reachable().iter().map(|x| *x).filter(|id| {
2949         // First, only worry about nodes which have a symbol name
2950         ccx.item_symbols().borrow().contains_key(id)
2951     }).filter(|&id| {
2952         // Next, we want to ignore some FFI functions that are not exposed from
2953         // this crate. Reachable FFI functions can be lumped into two
2954         // categories:
2955         //
2956         // 1. Those that are included statically via a static library
2957         // 2. Those included otherwise (e.g. dynamically or via a framework)
2958         //
2959         // Although our LLVM module is not literally emitting code for the
2960         // statically included symbols, it's an export of our library which
2961         // needs to be passed on to the linker and encoded in the metadata.
2962         //
2963         // As a result, if this id is an FFI item (foreign item) then we only
2964         // let it through if it's included statically.
2965         match ccx.tcx().map.get(id) {
2966             hir_map::NodeForeignItem(..) => {
2967                 ccx.sess().cstore.is_statically_included_foreign_item(id)
2968             }
2969             _ => true,
2970         }
2971     }).collect()
2972 }
2973
2974 pub fn trans_crate<'tcx>(tcx: &ty::ctxt<'tcx>,
2975                          mir_map: &MirMap<'tcx>,
2976                          analysis: ty::CrateAnalysis)
2977                          -> CrateTranslation {
2978     let ty::CrateAnalysis { export_map, reachable, name, .. } = analysis;
2979     let krate = tcx.map.krate();
2980
2981     let check_overflow = if let Some(v) = tcx.sess.opts.debugging_opts.force_overflow_checks {
2982         v
2983     } else {
2984         tcx.sess.opts.debug_assertions
2985     };
2986
2987     let check_dropflag = if let Some(v) = tcx.sess.opts.debugging_opts.force_dropflag_checks {
2988         v
2989     } else {
2990         tcx.sess.opts.debug_assertions
2991     };
2992
2993     // Before we touch LLVM, make sure that multithreading is enabled.
2994     unsafe {
2995         use std::sync::Once;
2996         static INIT: Once = Once::new();
2997         static mut POISONED: bool = false;
2998         INIT.call_once(|| {
2999             if llvm::LLVMStartMultithreaded() != 1 {
3000                 // use an extra bool to make sure that all future usage of LLVM
3001                 // cannot proceed despite the Once not running more than once.
3002                 POISONED = true;
3003             }
3004
3005             ::back::write::configure_llvm(&tcx.sess);
3006         });
3007
3008         if POISONED {
3009             tcx.sess.bug("couldn't enable multi-threaded LLVM");
3010         }
3011     }
3012
3013     let link_meta = link::build_link_meta(&tcx.sess, krate, name);
3014
3015     let codegen_units = tcx.sess.opts.cg.codegen_units;
3016     let shared_ccx = SharedCrateContext::new(&link_meta.crate_name,
3017                                              codegen_units,
3018                                              tcx,
3019                                              &mir_map,
3020                                              export_map,
3021                                              Sha256::new(),
3022                                              link_meta.clone(),
3023                                              reachable,
3024                                              check_overflow,
3025                                              check_dropflag);
3026
3027     {
3028         let ccx = shared_ccx.get_ccx(0);
3029
3030         // First, verify intrinsics.
3031         intrinsic::check_intrinsics(&ccx);
3032
3033         // Next, translate all items. See `TransModVisitor` for
3034         // details on why we walk in this particular way.
3035         {
3036             let _icx = push_ctxt("text");
3037             intravisit::walk_mod(&mut TransItemsWithinModVisitor { ccx: &ccx }, &krate.module);
3038             krate.visit_all_items(&mut TransModVisitor { ccx: &ccx });
3039         }
3040     }
3041
3042     for ccx in shared_ccx.iter() {
3043         if ccx.sess().opts.debuginfo != NoDebugInfo {
3044             debuginfo::finalize(&ccx);
3045         }
3046         for &(old_g, new_g) in ccx.statics_to_rauw().borrow().iter() {
3047             unsafe {
3048                 let bitcast = llvm::LLVMConstPointerCast(new_g, llvm::LLVMTypeOf(old_g));
3049                 llvm::LLVMReplaceAllUsesWith(old_g, bitcast);
3050                 llvm::LLVMDeleteGlobal(old_g);
3051             }
3052         }
3053     }
3054
3055     let reachable_symbol_ids = filter_reachable_ids(&shared_ccx);
3056
3057     // Translate the metadata.
3058     let metadata = write_metadata(&shared_ccx, krate, &reachable_symbol_ids);
3059
3060     if shared_ccx.sess().trans_stats() {
3061         let stats = shared_ccx.stats();
3062         println!("--- trans stats ---");
3063         println!("n_glues_created: {}", stats.n_glues_created.get());
3064         println!("n_null_glues: {}", stats.n_null_glues.get());
3065         println!("n_real_glues: {}", stats.n_real_glues.get());
3066
3067         println!("n_fns: {}", stats.n_fns.get());
3068         println!("n_monos: {}", stats.n_monos.get());
3069         println!("n_inlines: {}", stats.n_inlines.get());
3070         println!("n_closures: {}", stats.n_closures.get());
3071         println!("fn stats:");
3072         stats.fn_stats.borrow_mut().sort_by(|&(_, insns_a), &(_, insns_b)| {
3073             insns_b.cmp(&insns_a)
3074         });
3075         for tuple in stats.fn_stats.borrow().iter() {
3076             match *tuple {
3077                 (ref name, insns) => {
3078                     println!("{} insns, {}", insns, *name);
3079                 }
3080             }
3081         }
3082     }
3083     if shared_ccx.sess().count_llvm_insns() {
3084         for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
3085             println!("{:7} {}", *v, *k);
3086         }
3087     }
3088
3089     let modules = shared_ccx.iter()
3090         .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
3091         .collect();
3092
3093     let sess = shared_ccx.sess();
3094     let mut reachable_symbols = reachable_symbol_ids.iter().map(|id| {
3095         shared_ccx.item_symbols().borrow()[id].to_string()
3096     }).collect::<Vec<_>>();
3097     if sess.entry_fn.borrow().is_some() {
3098         reachable_symbols.push("main".to_string());
3099     }
3100
3101     // For the purposes of LTO, we add to the reachable set all of the upstream
3102     // reachable extern fns. These functions are all part of the public ABI of
3103     // the final product, so LTO needs to preserve them.
3104     if sess.lto() {
3105         sess.cstore.iter_crate_data(|cnum, _| {
3106             let syms = csearch::get_reachable_ids(&sess.cstore, cnum);
3107             reachable_symbols.extend(syms.into_iter().filter(|did| {
3108                 csearch::is_extern_fn(&sess.cstore, *did, shared_ccx.tcx()) ||
3109                 csearch::is_static(&sess.cstore, *did)
3110             }).map(|did| {
3111                 csearch::get_symbol(&sess.cstore, did)
3112             }));
3113         });
3114     }
3115
3116     if codegen_units > 1 {
3117         internalize_symbols(&shared_ccx,
3118                             &reachable_symbols.iter().map(|x| &x[..]).collect());
3119     }
3120
3121     if sess.target.target.options.is_like_msvc &&
3122        sess.crate_types.borrow().iter().any(|ct| *ct == config::CrateTypeRlib) {
3123         create_imps(&shared_ccx);
3124     }
3125
3126     let metadata_module = ModuleTranslation {
3127         llcx: shared_ccx.metadata_llcx(),
3128         llmod: shared_ccx.metadata_llmod(),
3129     };
3130     let no_builtins = attr::contains_name(&krate.attrs, "no_builtins");
3131
3132     CrateTranslation {
3133         modules: modules,
3134         metadata_module: metadata_module,
3135         link: link_meta,
3136         metadata: metadata,
3137         reachable: reachable_symbols,
3138         no_builtins: no_builtins,
3139     }
3140 }
3141
3142 /// We visit all the items in the krate and translate them.  We do
3143 /// this in two walks. The first walk just finds module items. It then
3144 /// walks the full contents of those module items and translates all
3145 /// the items within. Note that this entire process is O(n). The
3146 /// reason for this two phased walk is that each module is
3147 /// (potentially) placed into a distinct codegen-unit. This walk also
3148 /// ensures that the immediate contents of each module is processed
3149 /// entirely before we proceed to find more modules, helping to ensure
3150 /// an equitable distribution amongst codegen-units.
3151 pub struct TransModVisitor<'a, 'tcx: 'a> {
3152     pub ccx: &'a CrateContext<'a, 'tcx>,
3153 }
3154
3155 impl<'a, 'tcx, 'v> Visitor<'v> for TransModVisitor<'a, 'tcx> {
3156     fn visit_item(&mut self, i: &hir::Item) {
3157         match i.node {
3158             hir::ItemMod(_) => {
3159                 let item_ccx = self.ccx.rotate();
3160                 intravisit::walk_item(&mut TransItemsWithinModVisitor { ccx: &item_ccx }, i);
3161             }
3162             _ => { }
3163         }
3164     }
3165 }
3166
3167 /// Translates all the items within a given module. Expects owner to
3168 /// invoke `walk_item` on a module item. Ignores nested modules.
3169 pub struct TransItemsWithinModVisitor<'a, 'tcx: 'a> {
3170     pub ccx: &'a CrateContext<'a, 'tcx>,
3171 }
3172
3173 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemsWithinModVisitor<'a, 'tcx> {
3174     fn visit_nested_item(&mut self, item_id: hir::ItemId) {
3175         self.visit_item(self.ccx.tcx().map.expect_item(item_id.id));
3176     }
3177
3178     fn visit_item(&mut self, i: &hir::Item) {
3179         match i.node {
3180             hir::ItemMod(..) => {
3181                 // skip modules, they will be uncovered by the TransModVisitor
3182             }
3183             _ => {
3184                 trans_item(self.ccx, i);
3185                 intravisit::walk_item(self, i);
3186             }
3187         }
3188     }
3189 }