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