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