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