]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
auto merge of #17069 : eddyb/rust/visitor, r=pnkfelix
[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     in_return: bool
1327 }
1328
1329 impl CheckForNestedReturnsVisitor {
1330     fn explicit() -> CheckForNestedReturnsVisitor {
1331         CheckForNestedReturnsVisitor { found: false, in_return: false }
1332     }
1333     fn implicit() -> CheckForNestedReturnsVisitor {
1334         CheckForNestedReturnsVisitor { found: false, in_return: true }
1335     }
1336 }
1337
1338 impl<'v> Visitor<'v> for CheckForNestedReturnsVisitor {
1339     fn visit_expr(&mut self, e: &ast::Expr) {
1340         match e.node {
1341             ast::ExprRet(..) => {
1342                 if self.in_return {
1343                     self.found = true;
1344                 } else {
1345                     self.in_return = true;
1346                     visit::walk_expr(self, e);
1347                     self.in_return = false;
1348                 }
1349             }
1350             _ => visit::walk_expr(self, e)
1351         }
1352     }
1353 }
1354
1355 fn has_nested_returns(tcx: &ty::ctxt, id: ast::NodeId) -> bool {
1356     match tcx.map.find(id) {
1357         Some(ast_map::NodeItem(i)) => {
1358             match i.node {
1359                 ast::ItemFn(_, _, _, _, blk) => {
1360                     let mut explicit = CheckForNestedReturnsVisitor::explicit();
1361                     let mut implicit = CheckForNestedReturnsVisitor::implicit();
1362                     visit::walk_item(&mut explicit, &*i);
1363                     visit::walk_expr_opt(&mut implicit, &blk.expr);
1364                     explicit.found || implicit.found
1365                 }
1366                 _ => tcx.sess.bug("unexpected item variant in has_nested_returns")
1367             }
1368         }
1369         Some(ast_map::NodeTraitItem(trait_method)) => {
1370             match *trait_method {
1371                 ast::ProvidedMethod(m) => {
1372                     match m.node {
1373                         ast::MethDecl(_, _, _, _, _, _, blk, _) => {
1374                             let mut explicit = CheckForNestedReturnsVisitor::explicit();
1375                             let mut implicit = CheckForNestedReturnsVisitor::implicit();
1376                             visit::walk_method_helper(&mut explicit, &*m);
1377                             visit::walk_expr_opt(&mut implicit, &blk.expr);
1378                             explicit.found || implicit.found
1379                         }
1380                         ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1381                     }
1382                 }
1383                 ast::RequiredMethod(_) => {
1384                     tcx.sess.bug("unexpected variant: required trait method \
1385                                   in has_nested_returns")
1386                 }
1387             }
1388         }
1389         Some(ast_map::NodeImplItem(ref ii)) => {
1390             match **ii {
1391                 ast::MethodImplItem(ref m) => {
1392                     match m.node {
1393                         ast::MethDecl(_, _, _, _, _, _, blk, _) => {
1394                             let mut explicit = CheckForNestedReturnsVisitor::explicit();
1395                             let mut implicit = CheckForNestedReturnsVisitor::implicit();
1396                             visit::walk_method_helper(&mut explicit, &**m);
1397                             visit::walk_expr_opt(&mut implicit, &blk.expr);
1398                             explicit.found || implicit.found
1399                         }
1400                         ast::MethMac(_) => tcx.sess.bug("unexpanded macro")
1401                     }
1402                 }
1403             }
1404         }
1405         Some(ast_map::NodeExpr(e)) => {
1406             match e.node {
1407                 ast::ExprFnBlock(_, _, blk) |
1408                 ast::ExprProc(_, blk) |
1409                 ast::ExprUnboxedFn(_, _, _, blk) => {
1410                     let mut explicit = CheckForNestedReturnsVisitor::explicit();
1411                     let mut implicit = CheckForNestedReturnsVisitor::implicit();
1412                     visit::walk_expr(&mut explicit, &*e);
1413                     visit::walk_expr_opt(&mut implicit, &blk.expr);
1414                     explicit.found || implicit.found
1415                 }
1416                 _ => tcx.sess.bug("unexpected expr variant in has_nested_returns")
1417             }
1418         }
1419
1420         Some(ast_map::NodeVariant(..)) | Some(ast_map::NodeStructCtor(..)) => false,
1421
1422         // glue, shims, etc
1423         None if id == ast::DUMMY_NODE_ID => false,
1424
1425         _ => tcx.sess.bug(format!("unexpected variant in has_nested_returns: {}",
1426                                   tcx.map.path_to_string(id)).as_slice())
1427     }
1428 }
1429
1430 // NB: must keep 4 fns in sync:
1431 //
1432 //  - type_of_fn
1433 //  - create_datums_for_fn_args.
1434 //  - new_fn_ctxt
1435 //  - trans_args
1436 //
1437 // Be warned! You must call `init_function` before doing anything with the
1438 // returned function context.
1439 pub fn new_fn_ctxt<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
1440                              llfndecl: ValueRef,
1441                              id: ast::NodeId,
1442                              has_env: bool,
1443                              output_type: ty::t,
1444                              param_substs: &'a param_substs,
1445                              sp: Option<Span>,
1446                              block_arena: &'a TypedArena<common::BlockS<'a, 'tcx>>)
1447                              -> FunctionContext<'a, 'tcx> {
1448     param_substs.validate();
1449
1450     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1451            if id == -1 {
1452                "".to_string()
1453            } else {
1454                ccx.tcx().map.path_to_string(id).to_string()
1455            },
1456            id, param_substs.repr(ccx.tcx()));
1457
1458     let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1459     let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1460     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1461     let nested_returns = has_nested_returns(ccx.tcx(), id);
1462
1463     let mut fcx = FunctionContext {
1464           llfn: llfndecl,
1465           llenv: None,
1466           llretslotptr: Cell::new(None),
1467           alloca_insert_pt: Cell::new(None),
1468           llreturn: Cell::new(None),
1469           needs_ret_allocas: nested_returns,
1470           personality: Cell::new(None),
1471           caller_expects_out_pointer: uses_outptr,
1472           llargs: RefCell::new(NodeMap::new()),
1473           lllocals: RefCell::new(NodeMap::new()),
1474           llupvars: RefCell::new(NodeMap::new()),
1475           id: id,
1476           param_substs: param_substs,
1477           span: sp,
1478           block_arena: block_arena,
1479           ccx: ccx,
1480           debug_context: debug_context,
1481           scopes: RefCell::new(Vec::new())
1482     };
1483
1484     if has_env {
1485         fcx.llenv = Some(get_param(fcx.llfn, fcx.env_arg_pos() as c_uint))
1486     }
1487
1488     fcx
1489 }
1490
1491 /// Performs setup on a newly created function, creating the entry scope block
1492 /// and allocating space for the return pointer.
1493 pub fn init_function<'a, 'tcx>(fcx: &'a FunctionContext<'a, 'tcx>,
1494                                skip_retptr: bool,
1495                                output_type: ty::t) -> Block<'a, 'tcx> {
1496     let entry_bcx = fcx.new_temp_block("entry-block");
1497
1498     // Use a dummy instruction as the insertion point for all allocas.
1499     // This is later removed in FunctionContext::cleanup.
1500     fcx.alloca_insert_pt.set(Some(unsafe {
1501         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1502         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1503     }));
1504
1505     // This shouldn't need to recompute the return type,
1506     // as new_fn_ctxt did it already.
1507     let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1508
1509     if !return_type_is_void(fcx.ccx, substd_output_type) {
1510         // If the function returns nil/bot, there is no real return
1511         // value, so do not set `llretslotptr`.
1512         if !skip_retptr || fcx.caller_expects_out_pointer {
1513             // Otherwise, we normally allocate the llretslotptr, unless we
1514             // have been instructed to skip it for immediate return
1515             // values.
1516             fcx.llretslotptr.set(Some(make_return_slot_pointer(fcx, substd_output_type)));
1517         }
1518     }
1519
1520     entry_bcx
1521 }
1522
1523 // NB: must keep 4 fns in sync:
1524 //
1525 //  - type_of_fn
1526 //  - create_datums_for_fn_args.
1527 //  - new_fn_ctxt
1528 //  - trans_args
1529
1530 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1531     use middle::trans::datum::{ByRef, ByValue};
1532
1533     datum::Rvalue {
1534         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1535     }
1536 }
1537
1538 // work around bizarre resolve errors
1539 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1540 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1541
1542 // create_datums_for_fn_args: creates rvalue datums for each of the
1543 // incoming function arguments. These will later be stored into
1544 // appropriate lvalue datums.
1545 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1546                                  arg_tys: &[ty::t])
1547                                  -> Vec<RvalueDatum> {
1548     let _icx = push_ctxt("create_datums_for_fn_args");
1549
1550     // Return an array wrapping the ValueRefs that we get from `get_param` for
1551     // each argument into datums.
1552     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1553         let llarg = get_param(fcx.llfn, fcx.arg_pos(i) as c_uint);
1554         datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1555     }).collect()
1556 }
1557
1558 /// Creates rvalue datums for each of the incoming function arguments and
1559 /// tuples the arguments. These will later be stored into appropriate lvalue
1560 /// datums.
1561 ///
1562 /// FIXME(pcwalton): Reduce the amount of code bloat this is responsible for.
1563 fn create_datums_for_fn_args_under_call_abi(
1564         mut bcx: Block,
1565         arg_scope: cleanup::CustomScopeIndex,
1566         arg_tys: &[ty::t])
1567         -> Vec<RvalueDatum> {
1568     let mut result = Vec::new();
1569     for (i, &arg_ty) in arg_tys.iter().enumerate() {
1570         if i < arg_tys.len() - 1 {
1571             // Regular argument.
1572             let llarg = get_param(bcx.fcx.llfn, bcx.fcx.arg_pos(i) as c_uint);
1573             result.push(datum::Datum::new(llarg, arg_ty, arg_kind(bcx.fcx,
1574                                                                   arg_ty)));
1575             continue
1576         }
1577
1578         // This is the last argument. Tuple it.
1579         match ty::get(arg_ty).sty {
1580             ty::ty_tup(ref tupled_arg_tys) => {
1581                 let tuple_args_scope_id = cleanup::CustomScope(arg_scope);
1582                 let tuple =
1583                     unpack_datum!(bcx,
1584                                   datum::lvalue_scratch_datum(bcx,
1585                                                               arg_ty,
1586                                                               "tupled_args",
1587                                                               false,
1588                                                               tuple_args_scope_id,
1589                                                               (),
1590                                                               |(),
1591                                                                mut bcx,
1592                                                                llval| {
1593                         for (j, &tupled_arg_ty) in
1594                                     tupled_arg_tys.iter().enumerate() {
1595                             let llarg =
1596                                 get_param(bcx.fcx.llfn,
1597                                           bcx.fcx.arg_pos(i + j) as c_uint);
1598                             let lldest = GEPi(bcx, llval, [0, j]);
1599                             let datum = datum::Datum::new(
1600                                 llarg,
1601                                 tupled_arg_ty,
1602                                 arg_kind(bcx.fcx, tupled_arg_ty));
1603                             bcx = datum.store_to(bcx, lldest);
1604                         }
1605                         bcx
1606                     }));
1607                 let tuple = unpack_datum!(bcx,
1608                                           tuple.to_expr_datum()
1609                                                .to_rvalue_datum(bcx,
1610                                                                 "argtuple"));
1611                 result.push(tuple);
1612             }
1613             ty::ty_nil => {
1614                 let mode = datum::Rvalue::new(datum::ByValue);
1615                 result.push(datum::Datum::new(C_nil(bcx.ccx()),
1616                                               ty::mk_nil(),
1617                                               mode))
1618             }
1619             _ => {
1620                 bcx.tcx().sess.bug("last argument of a function with \
1621                                     `rust-call` ABI isn't a tuple?!")
1622             }
1623         };
1624
1625     }
1626
1627     result
1628 }
1629
1630 fn copy_args_to_allocas<'blk, 'tcx>(fcx: &FunctionContext<'blk, 'tcx>,
1631                                     arg_scope: cleanup::CustomScopeIndex,
1632                                     bcx: Block<'blk, 'tcx>,
1633                                     args: &[ast::Arg],
1634                                     arg_datums: Vec<RvalueDatum> )
1635                                     -> Block<'blk, 'tcx> {
1636     debug!("copy_args_to_allocas");
1637
1638     let _icx = push_ctxt("copy_args_to_allocas");
1639     let mut bcx = bcx;
1640
1641     let arg_scope_id = cleanup::CustomScope(arg_scope);
1642
1643     for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1644         // For certain mode/type combinations, the raw llarg values are passed
1645         // by value.  However, within the fn body itself, we want to always
1646         // have all locals and arguments be by-ref so that we can cancel the
1647         // cleanup and for better interaction with LLVM's debug info.  So, if
1648         // the argument would be passed by value, we store it into an alloca.
1649         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1650         // the event it's not truly needed.
1651
1652         bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1653
1654         if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1655             debuginfo::create_argument_metadata(bcx, &args[i]);
1656         }
1657     }
1658
1659     bcx
1660 }
1661
1662 fn copy_unboxed_closure_args_to_allocas<'blk, 'tcx>(
1663                                         mut bcx: Block<'blk, 'tcx>,
1664                                         arg_scope: cleanup::CustomScopeIndex,
1665                                         args: &[ast::Arg],
1666                                         arg_datums: Vec<RvalueDatum>,
1667                                         monomorphized_arg_types: &[ty::t])
1668                                         -> Block<'blk, 'tcx> {
1669     let _icx = push_ctxt("copy_unboxed_closure_args_to_allocas");
1670     let arg_scope_id = cleanup::CustomScope(arg_scope);
1671
1672     assert_eq!(arg_datums.len(), 1);
1673
1674     let arg_datum = arg_datums.move_iter().next().unwrap();
1675
1676     // Untuple the rest of the arguments.
1677     let tuple_datum =
1678         unpack_datum!(bcx,
1679                       arg_datum.to_lvalue_datum_in_scope(bcx,
1680                                                          "argtuple",
1681                                                          arg_scope_id));
1682     let empty = Vec::new();
1683     let untupled_arg_types = match ty::get(monomorphized_arg_types[0]).sty {
1684         ty::ty_tup(ref types) => types.as_slice(),
1685         ty::ty_nil => empty.as_slice(),
1686         _ => {
1687             bcx.tcx().sess.span_bug(args[0].pat.span,
1688                                     "first arg to `rust-call` ABI function \
1689                                      wasn't a tuple?!")
1690         }
1691     };
1692     for j in range(0, args.len()) {
1693         let tuple_element_type = untupled_arg_types[j];
1694         let tuple_element_datum =
1695             tuple_datum.get_element(bcx,
1696                                     tuple_element_type,
1697                                     |llval| GEPi(bcx, llval, [0, j]));
1698         let tuple_element_datum = tuple_element_datum.to_expr_datum();
1699         let tuple_element_datum =
1700             unpack_datum!(bcx,
1701                           tuple_element_datum.to_rvalue_datum(bcx,
1702                                                               "arg"));
1703         bcx = _match::store_arg(bcx,
1704                                 args[j].pat,
1705                                 tuple_element_datum,
1706                                 arg_scope_id);
1707
1708         if bcx.fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1709             debuginfo::create_argument_metadata(bcx, &args[j]);
1710         }
1711     }
1712
1713     bcx
1714 }
1715
1716 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1717 // and builds the return block.
1718 pub fn finish_fn<'blk, 'tcx>(fcx: &'blk FunctionContext<'blk, 'tcx>,
1719                              last_bcx: Block<'blk, 'tcx>,
1720                              retty: ty::t) {
1721     let _icx = push_ctxt("finish_fn");
1722
1723     // This shouldn't need to recompute the return type,
1724     // as new_fn_ctxt did it already.
1725     let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1726
1727     let ret_cx = match fcx.llreturn.get() {
1728         Some(llreturn) => {
1729             if !last_bcx.terminated.get() {
1730                 Br(last_bcx, llreturn);
1731             }
1732             raw_block(fcx, false, llreturn)
1733         }
1734         None => last_bcx
1735     };
1736     build_return_block(fcx, ret_cx, substd_retty);
1737     debuginfo::clear_source_location(fcx);
1738     fcx.cleanup();
1739 }
1740
1741 // Builds the return block for a function.
1742 pub fn build_return_block(fcx: &FunctionContext, ret_cx: Block, retty: ty::t) {
1743     if fcx.llretslotptr.get().is_none() ||
1744        (!fcx.needs_ret_allocas && fcx.caller_expects_out_pointer) {
1745         return RetVoid(ret_cx);
1746     }
1747
1748     let retslot = if fcx.needs_ret_allocas {
1749         Load(ret_cx, fcx.llretslotptr.get().unwrap())
1750     } else {
1751         fcx.llretslotptr.get().unwrap()
1752     };
1753     let retptr = Value(retslot);
1754     match retptr.get_dominating_store(ret_cx) {
1755         // If there's only a single store to the ret slot, we can directly return
1756         // the value that was stored and omit the store and the alloca
1757         Some(s) => {
1758             let retval = s.get_operand(0).unwrap().get();
1759             s.erase_from_parent();
1760
1761             if retptr.has_no_uses() {
1762                 retptr.erase_from_parent();
1763             }
1764
1765             let retval = if ty::type_is_bool(retty) {
1766                 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1767             } else {
1768                 retval
1769             };
1770
1771             if fcx.caller_expects_out_pointer {
1772                 store_ty(ret_cx, retval, get_param(fcx.llfn, 0), retty);
1773                 return RetVoid(ret_cx);
1774             } else {
1775                 return Ret(ret_cx, retval);
1776             }
1777         }
1778         // Otherwise, copy the return value to the ret slot
1779         None => {
1780             if fcx.caller_expects_out_pointer {
1781                 memcpy_ty(ret_cx, get_param(fcx.llfn, 0), retslot, retty);
1782                 return RetVoid(ret_cx);
1783             } else {
1784                 return Ret(ret_cx, load_ty(ret_cx, retslot, retty));
1785             }
1786         }
1787     }
1788 }
1789
1790 #[deriving(Clone, Eq, PartialEq)]
1791 pub enum IsUnboxedClosureFlag {
1792     NotUnboxedClosure,
1793     IsUnboxedClosure,
1794 }
1795
1796 // trans_closure: Builds an LLVM function out of a source function.
1797 // If the function closes over its environment a closure will be
1798 // returned.
1799 pub fn trans_closure(ccx: &CrateContext,
1800                      decl: &ast::FnDecl,
1801                      body: &ast::Block,
1802                      llfndecl: ValueRef,
1803                      param_substs: &param_substs,
1804                      id: ast::NodeId,
1805                      _attributes: &[ast::Attribute],
1806                      arg_types: Vec<ty::t>,
1807                      output_type: ty::t,
1808                      abi: Abi,
1809                      has_env: bool,
1810                      is_unboxed_closure: IsUnboxedClosureFlag,
1811                      maybe_load_env: <'blk, 'tcx> |Block<'blk, 'tcx>, ScopeId|
1812                                                   -> Block<'blk, 'tcx>) {
1813     ccx.stats().n_closures.set(ccx.stats().n_closures.get() + 1);
1814
1815     let _icx = push_ctxt("trans_closure");
1816     set_uwtable(llfndecl);
1817
1818     debug!("trans_closure(..., param_substs={})",
1819            param_substs.repr(ccx.tcx()));
1820
1821     let arena = TypedArena::new();
1822     let fcx = new_fn_ctxt(ccx,
1823                           llfndecl,
1824                           id,
1825                           has_env,
1826                           output_type,
1827                           param_substs,
1828                           Some(body.span),
1829                           &arena);
1830     let mut bcx = init_function(&fcx, false, output_type);
1831
1832     // cleanup scope for the incoming arguments
1833     let arg_scope = fcx.push_custom_cleanup_scope();
1834
1835     let block_ty = node_id_type(bcx, body.id);
1836
1837     // Set up arguments to the function.
1838     let monomorphized_arg_types =
1839         arg_types.iter()
1840                  .map(|at| monomorphize_type(bcx, *at))
1841                  .collect::<Vec<_>>();
1842     for monomorphized_arg_type in monomorphized_arg_types.iter() {
1843         debug!("trans_closure: monomorphized_arg_type: {}",
1844                ty_to_string(ccx.tcx(), *monomorphized_arg_type));
1845     }
1846     debug!("trans_closure: function lltype: {}",
1847            bcx.fcx.ccx.tn().val_to_string(bcx.fcx.llfn));
1848
1849     let arg_datums = if abi != RustCall {
1850         create_datums_for_fn_args(&fcx,
1851                                   monomorphized_arg_types.as_slice())
1852     } else {
1853         create_datums_for_fn_args_under_call_abi(
1854             bcx,
1855             arg_scope,
1856             monomorphized_arg_types.as_slice())
1857     };
1858
1859     bcx = match is_unboxed_closure {
1860         NotUnboxedClosure => {
1861             copy_args_to_allocas(&fcx,
1862                                  arg_scope,
1863                                  bcx,
1864                                  decl.inputs.as_slice(),
1865                                  arg_datums)
1866         }
1867         IsUnboxedClosure => {
1868             copy_unboxed_closure_args_to_allocas(
1869                 bcx,
1870                 arg_scope,
1871                 decl.inputs.as_slice(),
1872                 arg_datums,
1873                 monomorphized_arg_types.as_slice())
1874         }
1875     };
1876
1877     bcx = maybe_load_env(bcx, cleanup::CustomScope(arg_scope));
1878
1879     // Up until here, IR instructions for this function have explicitly not been annotated with
1880     // source code location, so we don't step into call setup code. From here on, source location
1881     // emitting should be enabled.
1882     debuginfo::start_emitting_source_locations(&fcx);
1883
1884     let dest = match fcx.llretslotptr.get() {
1885         Some(_) => expr::SaveIn(fcx.get_ret_slot(bcx, block_ty, "iret_slot")),
1886         None => {
1887             assert!(type_is_zero_size(bcx.ccx(), block_ty));
1888             expr::Ignore
1889         }
1890     };
1891
1892     // This call to trans_block is the place where we bridge between
1893     // translation calls that don't have a return value (trans_crate,
1894     // trans_mod, trans_item, et cetera) and those that do
1895     // (trans_block, trans_expr, et cetera).
1896     bcx = controlflow::trans_block(bcx, body, dest);
1897
1898     match dest {
1899         expr::SaveIn(slot) if fcx.needs_ret_allocas => {
1900             Store(bcx, slot, fcx.llretslotptr.get().unwrap());
1901         }
1902         _ => {}
1903     }
1904
1905     match fcx.llreturn.get() {
1906         Some(_) => {
1907             Br(bcx, fcx.return_exit_block());
1908             fcx.pop_custom_cleanup_scope(arg_scope);
1909         }
1910         None => {
1911             // Microoptimization writ large: avoid creating a separate
1912             // llreturn basic block
1913             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1914         }
1915     };
1916
1917     // Put return block after all other blocks.
1918     // This somewhat improves single-stepping experience in debugger.
1919     unsafe {
1920         let llreturn = fcx.llreturn.get();
1921         for &llreturn in llreturn.iter() {
1922             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1923         }
1924     }
1925
1926     // Insert the mandatory first few basic blocks before lltop.
1927     finish_fn(&fcx, bcx, output_type);
1928 }
1929
1930 // trans_fn: creates an LLVM function corresponding to a source language
1931 // function.
1932 pub fn trans_fn(ccx: &CrateContext,
1933                 decl: &ast::FnDecl,
1934                 body: &ast::Block,
1935                 llfndecl: ValueRef,
1936                 param_substs: &param_substs,
1937                 id: ast::NodeId,
1938                 attrs: &[ast::Attribute]) {
1939     let _s = StatRecorder::new(ccx, ccx.tcx().map.path_to_string(id).to_string());
1940     debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1941     let _icx = push_ctxt("trans_fn");
1942     let fn_ty = ty::node_id_to_type(ccx.tcx(), id);
1943     let arg_types = ty::ty_fn_args(fn_ty);
1944     let output_type = ty::ty_fn_ret(fn_ty);
1945     let abi = ty::ty_fn_abi(fn_ty);
1946     trans_closure(ccx,
1947                   decl,
1948                   body,
1949                   llfndecl,
1950                   param_substs,
1951                   id,
1952                   attrs,
1953                   arg_types,
1954                   output_type,
1955                   abi,
1956                   false,
1957                   NotUnboxedClosure,
1958                   |bcx, _| bcx);
1959 }
1960
1961 pub fn trans_enum_variant(ccx: &CrateContext,
1962                           _enum_id: ast::NodeId,
1963                           variant: &ast::Variant,
1964                           _args: &[ast::VariantArg],
1965                           disr: ty::Disr,
1966                           param_substs: &param_substs,
1967                           llfndecl: ValueRef) {
1968     let _icx = push_ctxt("trans_enum_variant");
1969
1970     trans_enum_variant_or_tuple_like_struct(
1971         ccx,
1972         variant.node.id,
1973         disr,
1974         param_substs,
1975         llfndecl);
1976 }
1977
1978 pub fn trans_named_tuple_constructor<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1979                                                  ctor_ty: ty::t,
1980                                                  disr: ty::Disr,
1981                                                  args: callee::CallArgs,
1982                                                  dest: expr::Dest) -> Result<'blk, 'tcx> {
1983
1984     let ccx = bcx.fcx.ccx;
1985     let tcx = ccx.tcx();
1986
1987     let result_ty = match ty::get(ctor_ty).sty {
1988         ty::ty_bare_fn(ref bft) => bft.sig.output,
1989         _ => ccx.sess().bug(
1990             format!("trans_enum_variant_constructor: \
1991                      unexpected ctor return type {}",
1992                      ctor_ty.repr(tcx)).as_slice())
1993     };
1994
1995     // Get location to store the result. If the user does not care about
1996     // the result, just make a stack slot
1997     let llresult = match dest {
1998         expr::SaveIn(d) => d,
1999         expr::Ignore => {
2000             if !type_is_zero_size(ccx, result_ty) {
2001                 alloc_ty(bcx, result_ty, "constructor_result")
2002             } else {
2003                 C_undef(type_of::type_of(ccx, result_ty))
2004             }
2005         }
2006     };
2007
2008     if !type_is_zero_size(ccx, result_ty) {
2009         match args {
2010             callee::ArgExprs(exprs) => {
2011                 let fields = exprs.iter().map(|x| *x).enumerate().collect::<Vec<_>>();
2012                 bcx = expr::trans_adt(bcx, result_ty, disr, fields.as_slice(),
2013                                       None, expr::SaveIn(llresult));
2014             }
2015             _ => ccx.sess().bug("expected expr as arguments for variant/struct tuple constructor")
2016         }
2017     }
2018
2019     // If the caller doesn't care about the result
2020     // drop the temporary we made
2021     let bcx = match dest {
2022         expr::SaveIn(_) => bcx,
2023         expr::Ignore => glue::drop_ty(bcx, llresult, result_ty)
2024     };
2025
2026     Result::new(bcx, llresult)
2027 }
2028
2029 pub fn trans_tuple_struct(ccx: &CrateContext,
2030                           _fields: &[ast::StructField],
2031                           ctor_id: ast::NodeId,
2032                           param_substs: &param_substs,
2033                           llfndecl: ValueRef) {
2034     let _icx = push_ctxt("trans_tuple_struct");
2035
2036     trans_enum_variant_or_tuple_like_struct(
2037         ccx,
2038         ctor_id,
2039         0,
2040         param_substs,
2041         llfndecl);
2042 }
2043
2044 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
2045                                            ctor_id: ast::NodeId,
2046                                            disr: ty::Disr,
2047                                            param_substs: &param_substs,
2048                                            llfndecl: ValueRef) {
2049     let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2050     let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
2051
2052     let result_ty = match ty::get(ctor_ty).sty {
2053         ty::ty_bare_fn(ref bft) => bft.sig.output,
2054         _ => ccx.sess().bug(
2055             format!("trans_enum_variant_or_tuple_like_struct: \
2056                      unexpected ctor return type {}",
2057                     ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
2058     };
2059
2060     let arena = TypedArena::new();
2061     let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
2062                           param_substs, None, &arena);
2063     let bcx = init_function(&fcx, false, result_ty);
2064
2065     assert!(!fcx.needs_ret_allocas);
2066
2067     let arg_tys = ty::ty_fn_args(ctor_ty);
2068
2069     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
2070
2071     if !type_is_zero_size(fcx.ccx, result_ty) {
2072         let dest = fcx.get_ret_slot(bcx, result_ty, "eret_slot");
2073         let repr = adt::represent_type(ccx, result_ty);
2074         for (i, arg_datum) in arg_datums.move_iter().enumerate() {
2075             let lldestptr = adt::trans_field_ptr(bcx,
2076                                                  &*repr,
2077                                                  dest,
2078                                                  disr,
2079                                                  i);
2080             arg_datum.store_to(bcx, lldestptr);
2081         }
2082         adt::trans_set_discr(bcx, &*repr, dest, disr);
2083     }
2084
2085     finish_fn(&fcx, bcx, result_ty);
2086 }
2087
2088 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
2089     let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
2090
2091     let levels = ccx.tcx().node_lint_levels.borrow();
2092     let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
2093     let lvlsrc = match levels.find(&(id, lint_id)) {
2094         None | Some(&(lint::Allow, _)) => return,
2095         Some(&lvlsrc) => lvlsrc,
2096     };
2097
2098     let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
2099     match *avar {
2100         adt::General(_, ref variants, _) => {
2101             for var in variants.iter() {
2102                 let mut size = 0;
2103                 for field in var.fields.iter().skip(1) {
2104                     // skip the discriminant
2105                     size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
2106                 }
2107                 sizes.push(size);
2108             }
2109         },
2110         _ => { /* its size is either constant or unimportant */ }
2111     }
2112
2113     let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
2114         |(l, s, li), (idx, &size)|
2115             if size > l {
2116                 (size, l, idx)
2117             } else if size > s {
2118                 (l, size, li)
2119             } else {
2120                 (l, s, li)
2121             }
2122     );
2123
2124     // we only warn if the largest variant is at least thrice as large as
2125     // the second-largest.
2126     if largest > slargest * 3 && slargest > 0 {
2127         // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
2128         // pass for the latter already ran.
2129         lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
2130                             lvlsrc, Some(sp),
2131                             format!("enum variant is more than three times larger \
2132                                      ({} bytes) than the next largest (ignoring padding)",
2133                                     largest).as_slice());
2134
2135         ccx.sess().span_note(enum_def.variants.get(largest_index).span,
2136                              "this variant is the largest");
2137     }
2138 }
2139
2140 pub struct TransItemVisitor<'a, 'tcx: 'a> {
2141     pub ccx: &'a CrateContext<'a, 'tcx>,
2142 }
2143
2144 impl<'a, 'tcx, 'v> Visitor<'v> for TransItemVisitor<'a, 'tcx> {
2145     fn visit_item(&mut self, i: &ast::Item) {
2146         trans_item(self.ccx, i);
2147     }
2148 }
2149
2150 /// Enum describing the origin of an LLVM `Value`, for linkage purposes.
2151 pub enum ValueOrigin {
2152     /// The LLVM `Value` is in this context because the corresponding item was
2153     /// assigned to the current compilation unit.
2154     OriginalTranslation,
2155     /// The `Value`'s corresponding item was assigned to some other compilation
2156     /// unit, but the `Value` was translated in this context anyway because the
2157     /// item is marked `#[inline]`.
2158     InlinedCopy,
2159 }
2160
2161 /// Set the appropriate linkage for an LLVM `ValueRef` (function or global).
2162 /// If the `llval` is the direct translation of a specific Rust item, `id`
2163 /// should be set to the `NodeId` of that item.  (This mapping should be
2164 /// 1-to-1, so monomorphizations and drop/visit glue should have `id` set to
2165 /// `None`.)  `llval_origin` indicates whether `llval` is the translation of an
2166 /// item assigned to `ccx`'s compilation unit or an inlined copy of an item
2167 /// assigned to a different compilation unit.
2168 pub fn update_linkage(ccx: &CrateContext,
2169                       llval: ValueRef,
2170                       id: Option<ast::NodeId>,
2171                       llval_origin: ValueOrigin) {
2172     match llval_origin {
2173         InlinedCopy => {
2174             // `llval` is a translation of an item defined in a separate
2175             // compilation unit.  This only makes sense if there are at least
2176             // two compilation units.
2177             assert!(ccx.sess().opts.cg.codegen_units > 1);
2178             // `llval` is a copy of something defined elsewhere, so use
2179             // `AvailableExternallyLinkage` to avoid duplicating code in the
2180             // output.
2181             llvm::SetLinkage(llval, llvm::AvailableExternallyLinkage);
2182             return;
2183         },
2184         OriginalTranslation => {},
2185     }
2186
2187     match id {
2188         Some(id) if ccx.reachable().contains(&id) => {
2189             llvm::SetLinkage(llval, llvm::ExternalLinkage);
2190         },
2191         _ => {
2192             // `id` does not refer to an item in `ccx.reachable`.
2193             if ccx.sess().opts.cg.codegen_units > 1 {
2194                 llvm::SetLinkage(llval, llvm::ExternalLinkage);
2195             } else {
2196                 llvm::SetLinkage(llval, llvm::InternalLinkage);
2197             }
2198         },
2199     }
2200 }
2201
2202 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
2203     let _icx = push_ctxt("trans_item");
2204
2205     let from_external = ccx.external_srcs().borrow().contains_key(&item.id);
2206
2207     match item.node {
2208       ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
2209         if !generics.is_type_parameterized() {
2210             let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
2211             // Ignore `trans_everywhere` for cross-crate inlined items
2212             // (`from_external`).  `trans_item` will be called once for each
2213             // compilation unit that references the item, so it will still get
2214             // translated everywhere it's needed.
2215             for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2216                 let llfn = get_item_val(ccx, item.id);
2217                 if abi != Rust {
2218                     foreign::trans_rust_fn_with_foreign_abi(ccx,
2219                                                             &**decl,
2220                                                             &**body,
2221                                                             item.attrs.as_slice(),
2222                                                             llfn,
2223                                                             &param_substs::empty(),
2224                                                             item.id,
2225                                                             None);
2226                 } else {
2227                     trans_fn(ccx,
2228                              &**decl,
2229                              &**body,
2230                              llfn,
2231                              &param_substs::empty(),
2232                              item.id,
2233                              item.attrs.as_slice());
2234                 }
2235                 update_linkage(ccx,
2236                                llfn,
2237                                Some(item.id),
2238                                if is_origin { OriginalTranslation } else { InlinedCopy });
2239             }
2240         }
2241
2242         // Be sure to travel more than just one layer deep to catch nested
2243         // items in blocks and such.
2244         let mut v = TransItemVisitor{ ccx: ccx };
2245         v.visit_block(&**body);
2246       }
2247       ast::ItemImpl(ref generics, _, _, ref impl_items) => {
2248         meth::trans_impl(ccx,
2249                          item.ident,
2250                          impl_items.as_slice(),
2251                          generics,
2252                          item.id);
2253       }
2254       ast::ItemMod(ref m) => {
2255         trans_mod(&ccx.rotate(), m);
2256       }
2257       ast::ItemEnum(ref enum_definition, _) => {
2258         enum_variant_size_lint(ccx, enum_definition, item.span, item.id);
2259       }
2260       ast::ItemStatic(_, m, ref expr) => {
2261           // Recurse on the expression to catch items in blocks
2262           let mut v = TransItemVisitor{ ccx: ccx };
2263           v.visit_expr(&**expr);
2264
2265           let trans_everywhere = attr::requests_inline(item.attrs.as_slice());
2266           for (ref ccx, is_origin) in ccx.maybe_iter(!from_external && trans_everywhere) {
2267               consts::trans_const(ccx, m, item.id);
2268
2269               let g = get_item_val(ccx, item.id);
2270               update_linkage(ccx,
2271                              g,
2272                              Some(item.id),
2273                              if is_origin { OriginalTranslation } else { InlinedCopy });
2274           }
2275
2276           // Do static_assert checking. It can't really be done much earlier
2277           // because we need to get the value of the bool out of LLVM
2278           if attr::contains_name(item.attrs.as_slice(), "static_assert") {
2279               if m == ast::MutMutable {
2280                   ccx.sess().span_fatal(expr.span,
2281                                         "cannot have static_assert on a mutable \
2282                                          static");
2283               }
2284
2285               let v = ccx.const_values().borrow().get_copy(&item.id);
2286               unsafe {
2287                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2288                       ccx.sess().span_fatal(expr.span, "static assertion failed");
2289                   }
2290               }
2291           }
2292       },
2293       ast::ItemForeignMod(ref foreign_mod) => {
2294         foreign::trans_foreign_mod(ccx, foreign_mod);
2295       }
2296       ast::ItemTrait(..) => {
2297         // Inside of this trait definition, we won't be actually translating any
2298         // functions, but the trait still needs to be walked. Otherwise default
2299         // methods with items will not get translated and will cause ICE's when
2300         // metadata time comes around.
2301         let mut v = TransItemVisitor{ ccx: ccx };
2302         visit::walk_item(&mut v, item);
2303       }
2304       _ => {/* fall through */ }
2305     }
2306 }
2307
2308 // Translate a module. Doing this amounts to translating the items in the
2309 // module; there ends up being no artifact (aside from linkage names) of
2310 // separate modules in the compiled program.  That's because modules exist
2311 // only as a convenience for humans working with the code, to organize names
2312 // and control visibility.
2313 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
2314     let _icx = push_ctxt("trans_mod");
2315     for item in m.items.iter() {
2316         trans_item(ccx, &**item);
2317     }
2318 }
2319
2320 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
2321                       llfn: ValueRef) {
2322     ccx.item_symbols().borrow_mut().insert(node_id, sym);
2323
2324     // The stack exhaustion lang item shouldn't have a split stack because
2325     // otherwise it would continue to be exhausted (bad), and both it and the
2326     // eh_personality functions need to be externally linkable.
2327     let def = ast_util::local_def(node_id);
2328     if ccx.tcx().lang_items.stack_exhausted() == Some(def) {
2329         unset_split_stack(llfn);
2330         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2331     }
2332     if ccx.tcx().lang_items.eh_personality() == Some(def) {
2333         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
2334     }
2335
2336
2337     if is_entry_fn(ccx.sess(), node_id) {
2338         create_entry_wrapper(ccx, sp, llfn);
2339     }
2340 }
2341
2342 fn register_fn(ccx: &CrateContext,
2343                sp: Span,
2344                sym: String,
2345                node_id: ast::NodeId,
2346                node_type: ty::t)
2347                -> ValueRef {
2348     match ty::get(node_type).sty {
2349         ty::ty_bare_fn(ref f) => {
2350             assert!(f.abi == Rust || f.abi == RustCall);
2351         }
2352         _ => fail!("expected bare rust fn")
2353     };
2354
2355     let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
2356     finish_register_fn(ccx, sp, sym, node_id, llfn);
2357     llfn
2358 }
2359
2360 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t)
2361                               -> llvm::AttrBuilder {
2362     use middle::ty::{BrAnon, ReLateBound};
2363
2364     let (fn_sig, abi, has_env) = match ty::get(fn_ty).sty {
2365         ty::ty_closure(ref f) => (f.sig.clone(), f.abi, true),
2366         ty::ty_bare_fn(ref f) => (f.sig.clone(), f.abi, false),
2367         ty::ty_unboxed_closure(closure_did, _) => {
2368             let unboxed_closures = ccx.tcx().unboxed_closures.borrow();
2369             let ref function_type = unboxed_closures.get(&closure_did)
2370                                                     .closure_type;
2371
2372             (function_type.sig.clone(), RustCall, true)
2373         }
2374         _ => ccx.sess().bug("expected closure or function.")
2375     };
2376
2377
2378     // Since index 0 is the return value of the llvm func, we start
2379     // at either 1 or 2 depending on whether there's an env slot or not
2380     let mut first_arg_offset = if has_env { 2 } else { 1 };
2381     let mut attrs = llvm::AttrBuilder::new();
2382     let ret_ty = fn_sig.output;
2383
2384     // These have an odd calling convention, so we need to manually
2385     // unpack the input ty's
2386     let input_tys = match ty::get(fn_ty).sty {
2387         ty::ty_unboxed_closure(_, _) => {
2388             assert!(abi == RustCall);
2389
2390             match ty::get(fn_sig.inputs[0]).sty {
2391                 ty::ty_nil => Vec::new(),
2392                 ty::ty_tup(ref inputs) => inputs.clone(),
2393                 _ => ccx.sess().bug("expected tuple'd inputs")
2394             }
2395         },
2396         ty::ty_bare_fn(_) if abi == RustCall => {
2397             let inputs = vec![fn_sig.inputs[0]];
2398
2399             match ty::get(fn_sig.inputs[1]).sty {
2400                 ty::ty_nil => inputs,
2401                 ty::ty_tup(ref t_in) => inputs.append(t_in.as_slice()),
2402                 _ => ccx.sess().bug("expected tuple'd inputs")
2403             }
2404         }
2405         _ => fn_sig.inputs.clone()
2406     };
2407
2408     // A function pointer is called without the declaration
2409     // available, so we have to apply any attributes with ABI
2410     // implications directly to the call instruction. Right now,
2411     // the only attribute we need to worry about is `sret`.
2412     if type_of::return_uses_outptr(ccx, ret_ty) {
2413         let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, ret_ty));
2414
2415         // The outptr can be noalias and nocapture because it's entirely
2416         // invisible to the program. We also know it's nonnull as well
2417         // as how many bytes we can dereference
2418         attrs.arg(1, llvm::StructRetAttribute)
2419              .arg(1, llvm::NoAliasAttribute)
2420              .arg(1, llvm::NoCaptureAttribute)
2421              .arg(1, llvm::DereferenceableAttribute(llret_sz));
2422
2423         // Add one more since there's an outptr
2424         first_arg_offset += 1;
2425     } else {
2426         // The `noalias` attribute on the return value is useful to a
2427         // function ptr caller.
2428         match ty::get(ret_ty).sty {
2429             // `~` pointer return values never alias because ownership
2430             // is transferred
2431             ty::ty_uniq(it) if !ty::type_is_sized(ccx.tcx(), it) => {}
2432             ty::ty_uniq(_) => {
2433                 attrs.ret(llvm::NoAliasAttribute);
2434             }
2435             _ => {}
2436         }
2437
2438         // We can also mark the return value as `dereferenceable` in certain cases
2439         match ty::get(ret_ty).sty {
2440             // These are not really pointers but pairs, (pointer, len)
2441             ty::ty_uniq(it) |
2442             ty::ty_rptr(_, ty::mt { ty: it, .. }) if !ty::type_is_sized(ccx.tcx(), it) => {}
2443             ty::ty_uniq(inner) | ty::ty_rptr(_, ty::mt { ty: inner, .. }) => {
2444                 let llret_sz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2445                 attrs.ret(llvm::DereferenceableAttribute(llret_sz));
2446             }
2447             _ => {}
2448         }
2449
2450         match ty::get(ret_ty).sty {
2451             ty::ty_bool => {
2452                 attrs.ret(llvm::ZExtAttribute);
2453             }
2454             _ => {}
2455         }
2456     }
2457
2458     for (idx, &t) in input_tys.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
2459         match ty::get(t).sty {
2460             // this needs to be first to prevent fat pointers from falling through
2461             _ if !type_is_immediate(ccx, t) => {
2462                 let llarg_sz = llsize_of_real(ccx, type_of::type_of(ccx, t));
2463
2464                 // For non-immediate arguments the callee gets its own copy of
2465                 // the value on the stack, so there are no aliases. It's also
2466                 // program-invisible so can't possibly capture
2467                 attrs.arg(idx, llvm::NoAliasAttribute)
2468                      .arg(idx, llvm::NoCaptureAttribute)
2469                      .arg(idx, llvm::DereferenceableAttribute(llarg_sz));
2470             }
2471
2472             ty::ty_bool => {
2473                 attrs.arg(idx, llvm::ZExtAttribute);
2474             }
2475
2476             // `~` pointer parameters never alias because ownership is transferred
2477             ty::ty_uniq(inner) => {
2478                 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, inner));
2479
2480                 attrs.arg(idx, llvm::NoAliasAttribute)
2481                      .arg(idx, llvm::DereferenceableAttribute(llsz));
2482             }
2483
2484             // The visit glue deals only with opaque pointers so we don't
2485             // actually know the concrete type of Self thus we don't know how
2486             // many bytes to mark as dereferenceable so instead we just mark
2487             // it as nonnull which still holds true
2488             ty::ty_rptr(b, ty::mt { ty: it, mutbl }) if match ty::get(it).sty {
2489                 ty::ty_param(_) => true, _ => false
2490             } && mutbl == ast::MutMutable => {
2491                 attrs.arg(idx, llvm::NoAliasAttribute)
2492                      .arg(idx, llvm::NonNullAttribute);
2493
2494                 match b {
2495                     ReLateBound(_, BrAnon(_)) => {
2496                         attrs.arg(idx, llvm::NoCaptureAttribute);
2497                     }
2498                     _ => {}
2499                 }
2500             }
2501
2502             // `&mut` pointer parameters never alias other parameters, or mutable global data
2503             //
2504             // `&T` where `T` contains no `UnsafeCell<U>` is immutable, and can be marked as both
2505             // `readonly` and `noalias`, as LLVM's definition of `noalias` is based solely on
2506             // memory dependencies rather than pointer equality
2507             ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable ||
2508                                   !ty::type_contents(ccx.tcx(), mt.ty).interior_unsafe() => {
2509
2510                 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2511                 attrs.arg(idx, llvm::NoAliasAttribute)
2512                      .arg(idx, llvm::DereferenceableAttribute(llsz));
2513
2514                 if mt.mutbl == ast::MutImmutable {
2515                     attrs.arg(idx, llvm::ReadOnlyAttribute);
2516                 }
2517
2518                 match b {
2519                     ReLateBound(_, BrAnon(_)) => {
2520                         attrs.arg(idx, llvm::NoCaptureAttribute);
2521                     }
2522                     _ => {}
2523                 }
2524             }
2525
2526             // When a reference in an argument has no named lifetime, it's impossible for that
2527             // reference to escape this function (returned or stored beyond the call by a closure).
2528             ty::ty_rptr(ReLateBound(_, BrAnon(_)), mt) => {
2529                 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2530                 attrs.arg(idx, llvm::NoCaptureAttribute)
2531                      .arg(idx, llvm::DereferenceableAttribute(llsz));
2532             }
2533
2534             // & pointer parameters are also never null and we know exactly how
2535             // many bytes we can dereference
2536             ty::ty_rptr(_, mt) => {
2537                 let llsz = llsize_of_real(ccx, type_of::type_of(ccx, mt.ty));
2538                 attrs.arg(idx, llvm::DereferenceableAttribute(llsz));
2539             }
2540             _ => ()
2541         }
2542     }
2543
2544     attrs
2545 }
2546
2547 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2548 pub fn register_fn_llvmty(ccx: &CrateContext,
2549                           sp: Span,
2550                           sym: String,
2551                           node_id: ast::NodeId,
2552                           cc: llvm::CallConv,
2553                           llfty: Type) -> ValueRef {
2554     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
2555
2556     let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
2557     finish_register_fn(ccx, sp, sym, node_id, llfn);
2558     llfn
2559 }
2560
2561 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2562     match *sess.entry_fn.borrow() {
2563         Some((entry_id, _)) => node_id == entry_id,
2564         None => false
2565     }
2566 }
2567
2568 // Create a _rust_main(args: ~[str]) function which will be called from the
2569 // runtime rust_start function
2570 pub fn create_entry_wrapper(ccx: &CrateContext,
2571                            _sp: Span,
2572                            main_llfn: ValueRef) {
2573     let et = ccx.sess().entry_type.get().unwrap();
2574     match et {
2575         config::EntryMain => {
2576             create_entry_fn(ccx, main_llfn, true);
2577         }
2578         config::EntryStart => create_entry_fn(ccx, main_llfn, false),
2579         config::EntryNone => {}    // Do nothing.
2580     }
2581
2582     fn create_entry_fn(ccx: &CrateContext,
2583                        rust_main: ValueRef,
2584                        use_start_lang_item: bool) {
2585         let llfty = Type::func([ccx.int_type(), Type::i8p(ccx).ptr_to()],
2586                                &ccx.int_type());
2587
2588         let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
2589
2590         // FIXME: #16581: Marking a symbol in the executable with `dllexport`
2591         // linkage forces MinGW's linker to output a `.reloc` section for ASLR
2592         if ccx.sess().targ_cfg.os == OsWindows {
2593             unsafe { llvm::LLVMRustSetDLLExportStorageClass(llfn) }
2594         }
2595
2596         let llbb = "top".with_c_str(|buf| {
2597             unsafe {
2598                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llfn, buf)
2599             }
2600         });
2601         let bld = ccx.raw_builder();
2602         unsafe {
2603             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2604
2605             let (start_fn, args) = if use_start_lang_item {
2606                 let start_def_id = match ccx.tcx().lang_items.require(StartFnLangItem) {
2607                     Ok(id) => id,
2608                     Err(s) => { ccx.sess().fatal(s.as_slice()); }
2609                 };
2610                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
2611                     get_item_val(ccx, start_def_id.node)
2612                 } else {
2613                     let start_fn_type = csearch::get_type(ccx.tcx(),
2614                                                           start_def_id).ty;
2615                     trans_external_path(ccx, start_def_id, start_fn_type)
2616                 };
2617
2618                 let args = {
2619                     let opaque_rust_main = "rust_main".with_c_str(|buf| {
2620                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
2621                     });
2622
2623                     vec!(
2624                         opaque_rust_main,
2625                         get_param(llfn, 0),
2626                         get_param(llfn, 1)
2627                      )
2628                 };
2629                 (start_fn, args)
2630             } else {
2631                 debug!("using user-defined start fn");
2632                 let args = vec!(
2633                     get_param(llfn, 0 as c_uint),
2634                     get_param(llfn, 1 as c_uint)
2635                 );
2636
2637                 (rust_main, args)
2638             };
2639
2640             let result = llvm::LLVMBuildCall(bld,
2641                                              start_fn,
2642                                              args.as_ptr(),
2643                                              args.len() as c_uint,
2644                                              noname());
2645
2646             llvm::LLVMBuildRet(bld, result);
2647         }
2648     }
2649 }
2650
2651 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2652                  ty: ty::t, attrs: &[ast::Attribute]) -> String {
2653     match ccx.external_srcs().borrow().find(&id) {
2654         Some(&did) => {
2655             let sym = csearch::get_symbol(&ccx.sess().cstore, did);
2656             debug!("found item {} in other crate...", sym);
2657             return sym;
2658         }
2659         None => {}
2660     }
2661
2662     match attr::first_attr_value_str_by_name(attrs, "export_name") {
2663         // Use provided name
2664         Some(name) => name.get().to_string(),
2665
2666         _ => ccx.tcx().map.with_path(id, |mut path| {
2667             if attr::contains_name(attrs, "no_mangle") {
2668                 // Don't mangle
2669                 path.last().unwrap().to_string()
2670             } else {
2671                 match weak_lang_items::link_name(attrs) {
2672                     Some(name) => name.get().to_string(),
2673                     None => {
2674                         // Usual name mangling
2675                         mangle_exported_name(ccx, path, ty, id)
2676                     }
2677                 }
2678             }
2679         })
2680     }
2681 }
2682
2683 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2684     debug!("get_item_val(id=`{:?}`)", id);
2685
2686     match ccx.item_vals().borrow().find_copy(&id) {
2687         Some(v) => return v,
2688         None => {}
2689     }
2690
2691     let item = ccx.tcx().map.get(id);
2692     let val = match item {
2693         ast_map::NodeItem(i) => {
2694             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2695             let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2696
2697             let v = match i.node {
2698                 ast::ItemStatic(_, mutbl, ref expr) => {
2699                     // If this static came from an external crate, then
2700                     // we need to get the symbol from csearch instead of
2701                     // using the current crate's name/version
2702                     // information in the hash of the symbol
2703                     debug!("making {}", sym);
2704                     let is_local = !ccx.external_srcs().borrow().contains_key(&id);
2705
2706                     // We need the translated value here, because for enums the
2707                     // LLVM type is not fully determined by the Rust type.
2708                     let (v, inlineable, _) = consts::const_expr(ccx, &**expr, is_local);
2709                     ccx.const_values().borrow_mut().insert(id, v);
2710                     let mut inlineable = inlineable;
2711
2712                     unsafe {
2713                         let llty = llvm::LLVMTypeOf(v);
2714                         let g = sym.as_slice().with_c_str(|buf| {
2715                             llvm::LLVMAddGlobal(ccx.llmod(), llty, buf)
2716                         });
2717
2718                         // Apply the `unnamed_addr` attribute if
2719                         // requested
2720                         if !ast_util::static_has_significant_address(
2721                                 mutbl,
2722                                 i.attrs.as_slice()) {
2723                             llvm::SetUnnamedAddr(g, true);
2724
2725                             // This is a curious case where we must make
2726                             // all of these statics inlineable. If a
2727                             // global is not tagged as `#[inline(never)]`,
2728                             // then LLVM won't coalesce globals unless they
2729                             // have an internal linkage type. This means that
2730                             // external crates cannot use this global.
2731                             // This is a problem for things like inner
2732                             // statics in generic functions, because the
2733                             // function will be inlined into another
2734                             // crate and then attempt to link to the
2735                             // static in the original crate, only to
2736                             // find that it's not there. On the other
2737                             // side of inlining, the crates knows to
2738                             // not declare this static as
2739                             // available_externally (because it isn't)
2740                             inlineable = true;
2741                         }
2742
2743                         if attr::contains_name(i.attrs.as_slice(),
2744                                                "thread_local") {
2745                             llvm::set_thread_local(g, true);
2746                         }
2747
2748                         if !inlineable {
2749                             debug!("{} not inlined", sym);
2750                             ccx.non_inlineable_statics().borrow_mut()
2751                                                       .insert(id);
2752                         }
2753
2754                         ccx.item_symbols().borrow_mut().insert(i.id, sym);
2755                         g
2756                     }
2757                 }
2758
2759                 ast::ItemFn(_, _, abi, _, _) => {
2760                     let llfn = if abi == Rust {
2761                         register_fn(ccx, i.span, sym, i.id, ty)
2762                     } else {
2763                         foreign::register_rust_fn_with_foreign_abi(ccx,
2764                                                                    i.span,
2765                                                                    sym,
2766                                                                    i.id)
2767                     };
2768                     set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2769                     llfn
2770                 }
2771
2772                 _ => fail!("get_item_val: weird result in table")
2773             };
2774
2775             match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2776                                                      "link_section") {
2777                 Some(sect) => unsafe {
2778                     sect.get().with_c_str(|buf| {
2779                         llvm::LLVMSetSection(v, buf);
2780                     })
2781                 },
2782                 None => ()
2783             }
2784
2785             v
2786         }
2787
2788         ast_map::NodeTraitItem(trait_method) => {
2789             debug!("get_item_val(): processing a NodeTraitItem");
2790             match *trait_method {
2791                 ast::RequiredMethod(_) => {
2792                     ccx.sess().bug("unexpected variant: required trait method in \
2793                                    get_item_val()");
2794                 }
2795                 ast::ProvidedMethod(m) => {
2796                     register_method(ccx, id, &*m)
2797                 }
2798             }
2799         }
2800
2801         ast_map::NodeImplItem(ii) => {
2802             match *ii {
2803                 ast::MethodImplItem(m) => register_method(ccx, id, &*m),
2804             }
2805         }
2806
2807         ast_map::NodeForeignItem(ni) => {
2808             match ni.node {
2809                 ast::ForeignItemFn(..) => {
2810                     let abi = ccx.tcx().map.get_foreign_abi(id);
2811                     let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2812                     let name = foreign::link_name(&*ni);
2813                     foreign::register_foreign_item_fn(ccx, abi, ty,
2814                                                       name.get().as_slice(),
2815                                                       Some(ni.span))
2816                 }
2817                 ast::ForeignItemStatic(..) => {
2818                     foreign::register_static(ccx, &*ni)
2819                 }
2820             }
2821         }
2822
2823         ast_map::NodeVariant(ref v) => {
2824             let llfn;
2825             let args = match v.node.kind {
2826                 ast::TupleVariantKind(ref args) => args,
2827                 ast::StructVariantKind(_) => {
2828                     fail!("struct variant kind unexpected in get_item_val")
2829                 }
2830             };
2831             assert!(args.len() != 0u);
2832             let ty = ty::node_id_to_type(ccx.tcx(), id);
2833             let parent = ccx.tcx().map.get_parent(id);
2834             let enm = ccx.tcx().map.expect_item(parent);
2835             let sym = exported_name(ccx,
2836                                     id,
2837                                     ty,
2838                                     enm.attrs.as_slice());
2839
2840             llfn = match enm.node {
2841                 ast::ItemEnum(_, _) => {
2842                     register_fn(ccx, (*v).span, sym, id, ty)
2843                 }
2844                 _ => fail!("NodeVariant, shouldn't happen")
2845             };
2846             set_inline_hint(llfn);
2847             llfn
2848         }
2849
2850         ast_map::NodeStructCtor(struct_def) => {
2851             // Only register the constructor if this is a tuple-like struct.
2852             let ctor_id = match struct_def.ctor_id {
2853                 None => {
2854                     ccx.sess().bug("attempt to register a constructor of \
2855                                     a non-tuple-like struct")
2856                 }
2857                 Some(ctor_id) => ctor_id,
2858             };
2859             let parent = ccx.tcx().map.get_parent(id);
2860             let struct_item = ccx.tcx().map.expect_item(parent);
2861             let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2862             let sym = exported_name(ccx,
2863                                     id,
2864                                     ty,
2865                                     struct_item.attrs
2866                                                .as_slice());
2867             let llfn = register_fn(ccx, struct_item.span,
2868                                    sym, ctor_id, ty);
2869             set_inline_hint(llfn);
2870             llfn
2871         }
2872
2873         ref variant => {
2874             ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2875                                    variant).as_slice())
2876         }
2877     };
2878
2879     // All LLVM globals and functions are initially created as external-linkage
2880     // declarations.  If `trans_item`/`trans_fn` later turns the declaration
2881     // into a definition, it adjusts the linkage then (using `update_linkage`).
2882     //
2883     // The exception is foreign items, which have their linkage set inside the
2884     // call to `foreign::register_*` above.  We don't touch the linkage after
2885     // that (`foreign::trans_foreign_mod` doesn't adjust the linkage like the
2886     // other item translation functions do).
2887
2888     ccx.item_vals().borrow_mut().insert(id, val);
2889     val
2890 }
2891
2892 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2893                    m: &ast::Method) -> ValueRef {
2894     let mty = ty::node_id_to_type(ccx.tcx(), id);
2895
2896     let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2897
2898     let llfn = register_fn(ccx, m.span, sym, id, mty);
2899     set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2900     llfn
2901 }
2902
2903 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2904     unsafe {
2905         return llvm::LLVMConstPtrToInt(v, ccx.int_type().to_ref());
2906     }
2907 }
2908
2909 pub fn crate_ctxt_to_encode_parms<'a, 'tcx>(cx: &'a SharedCrateContext<'tcx>,
2910                                             ie: encoder::EncodeInlinedItem<'a>)
2911                                             -> encoder::EncodeParams<'a, 'tcx> {
2912     encoder::EncodeParams {
2913         diag: cx.sess().diagnostic(),
2914         tcx: cx.tcx(),
2915         reexports2: cx.exp_map2(),
2916         item_symbols: cx.item_symbols(),
2917         non_inlineable_statics: cx.non_inlineable_statics(),
2918         link_meta: cx.link_meta(),
2919         cstore: &cx.sess().cstore,
2920         encode_inlined_item: ie,
2921         reachable: cx.reachable(),
2922     }
2923 }
2924
2925 pub fn write_metadata(cx: &SharedCrateContext, krate: &ast::Crate) -> Vec<u8> {
2926     use flate;
2927
2928     let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2929         *ty != config::CrateTypeExecutable
2930     });
2931     if !any_library {
2932         return Vec::new()
2933     }
2934
2935     let encode_inlined_item: encoder::EncodeInlinedItem =
2936         |ecx, rbml_w, ii| astencode::encode_inlined_item(ecx, rbml_w, ii);
2937
2938     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2939     let metadata = encoder::encode_metadata(encode_parms, krate);
2940     let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2941                      .append(match flate::deflate_bytes(metadata.as_slice()) {
2942                          Some(compressed) => compressed,
2943                          None => {
2944                              cx.sess().fatal("failed to compress metadata")
2945                          }
2946                      }.as_slice());
2947     let llmeta = C_bytes_in_context(cx.metadata_llcx(), compressed.as_slice());
2948     let llconst = C_struct_in_context(cx.metadata_llcx(), [llmeta], false);
2949     let name = format!("rust_metadata_{}_{}",
2950                        cx.link_meta().crate_name,
2951                        cx.link_meta().crate_hash);
2952     let llglobal = name.with_c_str(|buf| {
2953         unsafe {
2954             llvm::LLVMAddGlobal(cx.metadata_llmod(), val_ty(llconst).to_ref(), buf)
2955         }
2956     });
2957     unsafe {
2958         llvm::LLVMSetInitializer(llglobal, llconst);
2959         let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2960         name.unwrap_or("rust_metadata").with_c_str(|buf| {
2961             llvm::LLVMSetSection(llglobal, buf)
2962         });
2963     }
2964     return metadata;
2965 }
2966
2967 /// Find any symbols that are defined in one compilation unit, but not declared
2968 /// in any other compilation unit.  Give these symbols internal linkage.
2969 fn internalize_symbols(cx: &SharedCrateContext, reachable: &HashSet<String>) {
2970     use std::c_str::CString;
2971
2972     unsafe {
2973         let mut declared = HashSet::new();
2974
2975         let iter_globals = |llmod| {
2976             ValueIter {
2977                 cur: llvm::LLVMGetFirstGlobal(llmod),
2978                 step: llvm::LLVMGetNextGlobal,
2979             }
2980         };
2981
2982         let iter_functions = |llmod| {
2983             ValueIter {
2984                 cur: llvm::LLVMGetFirstFunction(llmod),
2985                 step: llvm::LLVMGetNextFunction,
2986             }
2987         };
2988
2989         // Collect all external declarations in all compilation units.
2990         for ccx in cx.iter() {
2991             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
2992                 let linkage = llvm::LLVMGetLinkage(val);
2993                 // We only care about external declarations (not definitions)
2994                 // and available_externally definitions.
2995                 if !(linkage == llvm::ExternalLinkage as c_uint &&
2996                      llvm::LLVMIsDeclaration(val) != 0) &&
2997                    !(linkage == llvm::AvailableExternallyLinkage as c_uint) {
2998                     continue
2999                 }
3000
3001                 let name = CString::new(llvm::LLVMGetValueName(val), false);
3002                 declared.insert(name);
3003             }
3004         }
3005
3006         // Examine each external definition.  If the definition is not used in
3007         // any other compilation unit, and is not reachable from other crates,
3008         // then give it internal linkage.
3009         for ccx in cx.iter() {
3010             for val in iter_globals(ccx.llmod()).chain(iter_functions(ccx.llmod())) {
3011                 // We only care about external definitions.
3012                 if !(llvm::LLVMGetLinkage(val) == llvm::ExternalLinkage as c_uint &&
3013                      llvm::LLVMIsDeclaration(val) == 0) {
3014                     continue
3015                 }
3016
3017                 let name = CString::new(llvm::LLVMGetValueName(val), false);
3018                 if !declared.contains(&name) &&
3019                    !reachable.contains_equiv(&name.as_str().unwrap()) {
3020                     llvm::SetLinkage(val, llvm::InternalLinkage);
3021                 }
3022             }
3023         }
3024     }
3025
3026
3027     struct ValueIter {
3028         cur: ValueRef,
3029         step: unsafe extern "C" fn(ValueRef) -> ValueRef,
3030     }
3031
3032     impl Iterator<ValueRef> for ValueIter {
3033         fn next(&mut self) -> Option<ValueRef> {
3034             let old = self.cur;
3035             if !old.is_null() {
3036                 self.cur = unsafe { (self.step)(old) };
3037                 Some(old)
3038             } else {
3039                 None
3040             }
3041         }
3042     }
3043 }
3044
3045 pub fn trans_crate(krate: ast::Crate,
3046                    analysis: CrateAnalysis) -> (ty::ctxt, CrateTranslation) {
3047     let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
3048
3049     // Before we touch LLVM, make sure that multithreading is enabled.
3050     unsafe {
3051         use std::sync::{Once, ONCE_INIT};
3052         static mut INIT: Once = ONCE_INIT;
3053         static mut POISONED: bool = false;
3054         INIT.doit(|| {
3055             if llvm::LLVMStartMultithreaded() != 1 {
3056                 // use an extra bool to make sure that all future usage of LLVM
3057                 // cannot proceed despite the Once not running more than once.
3058                 POISONED = true;
3059             }
3060         });
3061
3062         if POISONED {
3063             tcx.sess.bug("couldn't enable multi-threaded LLVM");
3064         }
3065     }
3066
3067     let link_meta = link::build_link_meta(&tcx.sess, &krate, name);
3068
3069     let codegen_units = tcx.sess.opts.cg.codegen_units;
3070     let shared_ccx = SharedCrateContext::new(link_meta.crate_name.as_slice(),
3071                                              codegen_units,
3072                                              tcx,
3073                                              exp_map2,
3074                                              Sha256::new(),
3075                                              link_meta.clone(),
3076                                              reachable);
3077
3078     {
3079         let ccx = shared_ccx.get_ccx(0);
3080
3081         // First, verify intrinsics.
3082         intrinsic::check_intrinsics(&ccx);
3083
3084         // Next, translate the module.
3085         {
3086             let _icx = push_ctxt("text");
3087             trans_mod(&ccx, &krate.module);
3088         }
3089     }
3090
3091     for ccx in shared_ccx.iter() {
3092         glue::emit_tydescs(&ccx);
3093         if ccx.sess().opts.debuginfo != NoDebugInfo {
3094             debuginfo::finalize(&ccx);
3095         }
3096     }
3097
3098     // Translate the metadata.
3099     let metadata = write_metadata(&shared_ccx, &krate);
3100
3101     if shared_ccx.sess().trans_stats() {
3102         let stats = shared_ccx.stats();
3103         println!("--- trans stats ---");
3104         println!("n_static_tydescs: {}", stats.n_static_tydescs.get());
3105         println!("n_glues_created: {}", stats.n_glues_created.get());
3106         println!("n_null_glues: {}", stats.n_null_glues.get());
3107         println!("n_real_glues: {}", stats.n_real_glues.get());
3108
3109         println!("n_fns: {}", stats.n_fns.get());
3110         println!("n_monos: {}", stats.n_monos.get());
3111         println!("n_inlines: {}", stats.n_inlines.get());
3112         println!("n_closures: {}", stats.n_closures.get());
3113         println!("fn stats:");
3114         stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
3115             insns_b.cmp(&insns_a)
3116         });
3117         for tuple in stats.fn_stats.borrow().iter() {
3118             match *tuple {
3119                 (ref name, ms, insns) => {
3120                     println!("{} insns, {} ms, {}", insns, ms, *name);
3121                 }
3122             }
3123         }
3124     }
3125     if shared_ccx.sess().count_llvm_insns() {
3126         for (k, v) in shared_ccx.stats().llvm_insns.borrow().iter() {
3127             println!("{:7u} {}", *v, *k);
3128         }
3129     }
3130
3131     let modules = shared_ccx.iter()
3132         .map(|ccx| ModuleTranslation { llcx: ccx.llcx(), llmod: ccx.llmod() })
3133         .collect();
3134
3135     let mut reachable: Vec<String> = shared_ccx.reachable().iter().filter_map(|id| {
3136         shared_ccx.item_symbols().borrow().find(id).map(|s| s.to_string())
3137     }).collect();
3138
3139     // For the purposes of LTO, we add to the reachable set all of the upstream
3140     // reachable extern fns. These functions are all part of the public ABI of
3141     // the final product, so LTO needs to preserve them.
3142     shared_ccx.sess().cstore.iter_crate_data(|cnum, _| {
3143         let syms = csearch::get_reachable_extern_fns(&shared_ccx.sess().cstore, cnum);
3144         reachable.extend(syms.move_iter().map(|did| {
3145             csearch::get_symbol(&shared_ccx.sess().cstore, did)
3146         }));
3147     });
3148
3149     // Make sure that some other crucial symbols are not eliminated from the
3150     // module. This includes the main function, the crate map (used for debug
3151     // log settings and I/O), and finally the curious rust_stack_exhausted
3152     // symbol. This symbol is required for use by the libmorestack library that
3153     // we link in, so we must ensure that this symbol is not internalized (if
3154     // defined in the crate).
3155     reachable.push("main".to_string());
3156     reachable.push("rust_stack_exhausted".to_string());
3157
3158     // referenced from .eh_frame section on some platforms
3159     reachable.push("rust_eh_personality".to_string());
3160     // referenced from rt/rust_try.ll
3161     reachable.push("rust_eh_personality_catch".to_string());
3162
3163     if codegen_units > 1 {
3164         internalize_symbols(&shared_ccx, &reachable.iter().map(|x| x.clone()).collect());
3165     }
3166
3167     let metadata_module = ModuleTranslation {
3168         llcx: shared_ccx.metadata_llcx(),
3169         llmod: shared_ccx.metadata_llmod(),
3170     };
3171     let formats = shared_ccx.tcx().dependency_formats.borrow().clone();
3172     let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
3173
3174     let translation = CrateTranslation {
3175         modules: modules,
3176         metadata_module: metadata_module,
3177         link: link_meta,
3178         metadata: metadata,
3179         reachable: reachable,
3180         crate_formats: formats,
3181         no_builtins: no_builtins,
3182     };
3183
3184     (shared_ccx.take_tcx(), translation)
3185 }