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