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