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