]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
auto merge of #15726 : aturon/rust/macro-stability, r=alexcrichton
[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::session::Session;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
34 use llvm;
35 use llvm::{ModuleRef, ValueRef, BasicBlockRef};
36 use llvm::{Vector};
37 use metadata::{csearch, encoder, loader};
38 use lint;
39 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::weak_lang_items;
42 use middle::subst;
43 use middle::subst::Subst;
44 use middle::trans::_match;
45 use middle::trans::adt;
46 use middle::trans::build::*;
47 use middle::trans::builder::{Builder, noname};
48 use middle::trans::callee;
49 use middle::trans::cleanup;
50 use middle::trans::cleanup::CleanupMethods;
51 use middle::trans::common::*;
52 use middle::trans::consts;
53 use middle::trans::controlflow;
54 use middle::trans::datum;
55 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
56 use middle::trans::debuginfo;
57 use middle::trans::expr;
58 use middle::trans::foreign;
59 use middle::trans::glue;
60 use middle::trans::inline;
61 use middle::trans::intrinsic;
62 use middle::trans::machine;
63 use middle::trans::machine::{llalign_of_min, llsize_of, llsize_of_real};
64 use middle::trans::meth;
65 use middle::trans::monomorphize;
66 use middle::trans::tvec;
67 use middle::trans::type_::Type;
68 use middle::trans::type_of;
69 use middle::trans::type_of::*;
70 use middle::trans::value::Value;
71 use middle::ty;
72 use middle::typeck;
73 use util::common::indenter;
74 use util::ppaux::{Repr, ty_to_string};
75 use util::sha2::Sha256;
76 use util::nodemap::NodeMap;
77
78 use arena::TypedArena;
79 use libc::{c_uint, uint64_t};
80 use std::c_str::ToCStr;
81 use std::cell::{Cell, RefCell};
82 use std::rc::Rc;
83 use std::{i8, i16, i32, i64};
84 use std::gc::Gc;
85 use syntax::abi::{X86, X86_64, Arm, Mips, Mipsel, Rust, RustIntrinsic};
86 use syntax::ast_util::{local_def, is_local};
87 use syntax::attr::AttrMetaMethods;
88 use syntax::attr;
89 use syntax::codemap::Span;
90 use syntax::parse::token::InternedString;
91 use syntax::visit::Visitor;
92 use syntax::visit;
93 use syntax::{ast, ast_util, ast_map};
94
95 use time;
96
97 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
98
99 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
100     match task_local_insn_key.get() {
101         Some(ctx) => blk(ctx.borrow().as_slice()),
102         None => ()
103     }
104 }
105
106 pub fn init_insn_ctxt() {
107     task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
108 }
109
110 pub struct _InsnCtxt {
111     _cannot_construct_outside_of_this_module: ()
112 }
113
114 #[unsafe_destructor]
115 impl Drop for _InsnCtxt {
116     fn drop(&mut self) {
117         match task_local_insn_key.get() {
118             Some(ctx) => { ctx.borrow_mut().pop(); }
119             None => {}
120         }
121     }
122 }
123
124 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
125     debug!("new InsnCtxt: {}", s);
126     match task_local_insn_key.get() {
127         Some(ctx) => ctx.borrow_mut().push(s),
128         None => {}
129     }
130     _InsnCtxt { _cannot_construct_outside_of_this_module: () }
131 }
132
133 pub struct StatRecorder<'a> {
134     ccx: &'a CrateContext,
135     name: Option<String>,
136     start: u64,
137     istart: uint,
138 }
139
140 impl<'a> StatRecorder<'a> {
141     pub fn new(ccx: &'a CrateContext, name: String) -> StatRecorder<'a> {
142         let start = if ccx.sess().trans_stats() {
143             time::precise_time_ns()
144         } else {
145             0
146         };
147         let istart = ccx.stats.n_llvm_insns.get();
148         StatRecorder {
149             ccx: ccx,
150             name: Some(name),
151             start: start,
152             istart: istart,
153         }
154     }
155 }
156
157 #[unsafe_destructor]
158 impl<'a> Drop for StatRecorder<'a> {
159     fn drop(&mut self) {
160         if self.ccx.sess().trans_stats() {
161             let end = time::precise_time_ns();
162             let elapsed = ((end - self.start) / 1_000_000) as uint;
163             let iend = self.ccx.stats.n_llvm_insns.get();
164             self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
165                                                        elapsed,
166                                                        iend - self.istart));
167             self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
168             // Reset LLVM insn count to avoid compound costs.
169             self.ccx.stats.n_llvm_insns.set(self.istart);
170         }
171     }
172 }
173
174 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
175 fn decl_fn(ccx: &CrateContext, name: &str, cc: llvm::CallConv,
176            ty: Type, output: ty::t) -> ValueRef {
177
178     let llfn: ValueRef = name.with_c_str(|buf| {
179         unsafe {
180             llvm::LLVMGetOrInsertFunction(ccx.llmod, buf, ty.to_ref())
181         }
182     });
183
184     match ty::get(output).sty {
185         // functions returning bottom may unwind, but can never return normally
186         ty::ty_bot => {
187             unsafe {
188                 llvm::LLVMAddFunctionAttribute(llfn,
189                                                llvm::FunctionIndex as c_uint,
190                                                llvm::NoReturnAttribute as uint64_t)
191             }
192         }
193         _ => {}
194     }
195
196     if ccx.tcx.sess.opts.cg.no_redzone {
197         unsafe {
198             llvm::LLVMAddFunctionAttribute(llfn,
199                                            llvm::FunctionIndex as c_uint,
200                                            llvm::NoRedZoneAttribute as uint64_t)
201         }
202     }
203
204     llvm::SetFunctionCallConv(llfn, cc);
205     // Function addresses in Rust are never significant, allowing functions to be merged.
206     llvm::SetUnnamedAddr(llfn, true);
207
208     if ccx.is_split_stack_supported() {
209         set_split_stack(llfn);
210     }
211
212     llfn
213 }
214
215 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
216 pub fn decl_cdecl_fn(ccx: &CrateContext,
217                      name: &str,
218                      ty: Type,
219                      output: ty::t) -> ValueRef {
220     decl_fn(ccx, name, llvm::CCallConv, ty, output)
221 }
222
223 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
224 pub fn get_extern_fn(ccx: &CrateContext,
225                      externs: &mut ExternMap,
226                      name: &str,
227                      cc: llvm::CallConv,
228                      ty: Type,
229                      output: ty::t)
230                      -> ValueRef {
231     match externs.find_equiv(&name) {
232         Some(n) => return *n,
233         None => {}
234     }
235     let f = decl_fn(ccx, name, cc, ty, output);
236     externs.insert(name.to_string(), f);
237     f
238 }
239
240 fn get_extern_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str, did: ast::DefId) -> ValueRef {
241     match ccx.externs.borrow().find_equiv(&name) {
242         Some(n) => return *n,
243         None => ()
244     }
245
246     let f = decl_rust_fn(ccx, fn_ty, name);
247
248     csearch::get_item_attrs(&ccx.sess().cstore, did, |attrs| {
249         set_llvm_fn_attrs(attrs.as_slice(), f)
250     });
251
252     ccx.externs.borrow_mut().insert(name.to_string(), f);
253     f
254 }
255
256 pub fn decl_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
257     let (inputs, output, has_env) = match ty::get(fn_ty).sty {
258         ty::ty_bare_fn(ref f) => (f.sig.inputs.clone(), f.sig.output, false),
259         ty::ty_closure(ref f) => (f.sig.inputs.clone(), f.sig.output, true),
260         _ => fail!("expected closure or fn")
261     };
262
263     let llfty = type_of_rust_fn(ccx, has_env, inputs.as_slice(), output);
264     let llfn = decl_fn(ccx, name, llvm::CCallConv, llfty, output);
265     let attrs = get_fn_llvm_attributes(ccx, fn_ty);
266     for &(idx, attr) in attrs.iter() {
267         unsafe {
268             llvm::LLVMAddFunctionAttribute(llfn, idx as c_uint, attr);
269         }
270     }
271
272     llfn
273 }
274
275 pub fn decl_internal_rust_fn(ccx: &CrateContext, fn_ty: ty::t, name: &str) -> ValueRef {
276     let llfn = decl_rust_fn(ccx, fn_ty, name);
277     llvm::SetLinkage(llfn, llvm::InternalLinkage);
278     llfn
279 }
280
281 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
282                         name: &str, ty: Type) -> ValueRef {
283     match externs.find_equiv(&name) {
284         Some(n) => return *n,
285         None => ()
286     }
287     unsafe {
288         let c = name.with_c_str(|buf| {
289             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
290         });
291         externs.insert(name.to_string(), c);
292         return c;
293     }
294 }
295
296 // Returns a pointer to the body for the box. The box may be an opaque
297 // box. The result will be casted to the type of body_t, if it is statically
298 // known.
299 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
300     let _icx = push_ctxt("at_box_body");
301     let ccx = bcx.ccx();
302     let ty = Type::at_box(ccx, type_of(ccx, body_t));
303     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
304     GEPi(bcx, boxptr, [0u, abi::box_field_body])
305 }
306
307 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
308     match bcx.tcx().lang_items.require(it) {
309         Ok(id) => id,
310         Err(s) => {
311             bcx.sess().fatal(format!("allocation of `{}` {}",
312                                      bcx.ty_to_string(info_ty),
313                                      s).as_slice());
314         }
315     }
316 }
317
318 // The following malloc_raw_dyn* functions allocate a box to contain
319 // a given type, but with a potentially dynamic size.
320
321 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
322                           ptr_ty: ty::t,
323                           size: ValueRef,
324                           align: ValueRef)
325                           -> Result<'a> {
326     let _icx = push_ctxt("malloc_raw_exchange");
327     let ccx = bcx.ccx();
328
329     // Allocate space:
330     let r = callee::trans_lang_call(bcx,
331         require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
332         [size, align],
333         None);
334
335     let llty_ptr = type_of::type_of(ccx, ptr_ty);
336     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
337 }
338
339 pub fn malloc_raw_dyn_managed<'a>(
340                       bcx: &'a Block<'a>,
341                       t: ty::t,
342                       alloc_fn: LangItem,
343                       size: ValueRef)
344                       -> Result<'a> {
345     let _icx = push_ctxt("malloc_raw_managed");
346     let ccx = bcx.ccx();
347
348     let langcall = require_alloc_fn(bcx, t, alloc_fn);
349
350     // Grab the TypeRef type of box_ptr_ty.
351     let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
352     let llty = type_of(ccx, box_ptr_ty);
353     let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
354
355     // Allocate space:
356     let drop_glue = glue::get_drop_glue(ccx, t);
357     let r = callee::trans_lang_call(
358         bcx,
359         langcall,
360         [
361             PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
362             size,
363             llalign
364         ],
365         None);
366     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
367 }
368
369 // Type descriptor and type glue stuff
370
371 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
372     match ccx.tydescs.borrow().find(&t) {
373         Some(inf) => return inf.clone(),
374         _ => { }
375     }
376
377     ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
378     let inf = Rc::new(glue::declare_tydesc(ccx, t));
379
380     ccx.tydescs.borrow_mut().insert(t, inf.clone());
381     inf
382 }
383
384 #[allow(dead_code)] // useful
385 pub fn set_optimize_for_size(f: ValueRef) {
386     llvm::SetFunctionAttribute(f, llvm::OptimizeForSizeAttribute)
387 }
388
389 pub fn set_no_inline(f: ValueRef) {
390     llvm::SetFunctionAttribute(f, llvm::NoInlineAttribute)
391 }
392
393 #[allow(dead_code)] // useful
394 pub fn set_no_unwind(f: ValueRef) {
395     llvm::SetFunctionAttribute(f, llvm::NoUnwindAttribute)
396 }
397
398 // Tell LLVM to emit the information necessary to unwind the stack for the
399 // function f.
400 pub fn set_uwtable(f: ValueRef) {
401     llvm::SetFunctionAttribute(f, llvm::UWTableAttribute)
402 }
403
404 pub fn set_inline_hint(f: ValueRef) {
405     llvm::SetFunctionAttribute(f, llvm::InlineHintAttribute)
406 }
407
408 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
409     use syntax::attr::*;
410     // Set the inline hint if there is one
411     match find_inline_attr(attrs) {
412         InlineHint   => set_inline_hint(llfn),
413         InlineAlways => set_always_inline(llfn),
414         InlineNever  => set_no_inline(llfn),
415         InlineNone   => { /* fallthrough */ }
416     }
417
418     // Add the no-split-stack attribute if requested
419     if contains_name(attrs, "no_split_stack") {
420         unset_split_stack(llfn);
421     }
422
423     if contains_name(attrs, "cold") {
424         unsafe {
425             llvm::LLVMAddFunctionAttribute(llfn,
426                                            llvm::FunctionIndex as c_uint,
427                                            llvm::ColdAttribute as uint64_t)
428         }
429     }
430 }
431
432 pub fn set_always_inline(f: ValueRef) {
433     llvm::SetFunctionAttribute(f, llvm::AlwaysInlineAttribute)
434 }
435
436 pub fn set_split_stack(f: ValueRef) {
437     "split-stack".with_c_str(|buf| {
438         unsafe { llvm::LLVMAddFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
439     })
440 }
441
442 pub fn unset_split_stack(f: ValueRef) {
443     "split-stack".with_c_str(|buf| {
444         unsafe { llvm::LLVMRemoveFunctionAttrString(f, llvm::FunctionIndex as c_uint, buf); }
445     })
446 }
447
448 // Double-check that we never ask LLVM to declare the same symbol twice. It
449 // silently mangles such symbols, breaking our linkage model.
450 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: String) {
451     if ccx.all_llvm_symbols.borrow().contains(&sym) {
452         ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
453     }
454     ccx.all_llvm_symbols.borrow_mut().insert(sym);
455 }
456
457
458 pub fn get_res_dtor(ccx: &CrateContext,
459                     did: ast::DefId,
460                     t: ty::t,
461                     parent_id: ast::DefId,
462                     substs: &subst::Substs)
463                  -> ValueRef {
464     let _icx = push_ctxt("trans_res_dtor");
465     let did = if did.krate != ast::LOCAL_CRATE {
466         inline::maybe_instantiate_inline(ccx, did)
467     } else {
468         did
469     };
470
471     if !substs.types.is_empty() {
472         assert_eq!(did.krate, ast::LOCAL_CRATE);
473
474         let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
475         let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None);
476
477         val
478     } else if did.krate == ast::LOCAL_CRATE {
479         get_item_val(ccx, did.node)
480     } else {
481         let tcx = ccx.tcx();
482         let name = csearch::get_symbol(&ccx.sess().cstore, did);
483         let class_ty = ty::lookup_item_type(tcx, parent_id).ty.subst(tcx, substs);
484         let llty = type_of_dtor(ccx, class_ty);
485         let dtor_ty = ty::mk_ctor_fn(ccx.tcx(), ast::DUMMY_NODE_ID,
486                                      [glue::get_drop_glue_type(ccx, t)], ty::mk_nil());
487         get_extern_fn(ccx,
488                       &mut *ccx.externs.borrow_mut(),
489                       name.as_slice(),
490                       llvm::CCallConv,
491                       llty,
492                       dtor_ty)
493     }
494 }
495
496 // Structural comparison: a rather involved form of glue.
497 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
498     if cx.sess().opts.cg.save_temps {
499         s.with_c_str(|buf| {
500             unsafe {
501                 llvm::LLVMSetValueName(v, buf)
502             }
503         })
504     }
505 }
506
507
508 // Used only for creating scalar comparison glue.
509 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
510
511 pub fn compare_scalar_types<'a>(
512                             cx: &'a Block<'a>,
513                             lhs: ValueRef,
514                             rhs: ValueRef,
515                             t: ty::t,
516                             op: ast::BinOp)
517                             -> Result<'a> {
518     let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
519
520     match ty::get(t).sty {
521         ty::ty_nil => f(nil_type),
522         ty::ty_bool | ty::ty_ptr(_) |
523         ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
524         ty::ty_int(_) => f(signed_int),
525         ty::ty_float(_) => f(floating_point),
526             // Should never get here, because t is scalar.
527         _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
528     }
529 }
530
531
532 // A helper function to do the actual comparison of scalar values.
533 pub fn compare_scalar_values<'a>(
534                              cx: &'a Block<'a>,
535                              lhs: ValueRef,
536                              rhs: ValueRef,
537                              nt: scalar_type,
538                              op: ast::BinOp)
539                              -> ValueRef {
540     let _icx = push_ctxt("compare_scalar_values");
541     fn die(cx: &Block) -> ! {
542         cx.sess().bug("compare_scalar_values: must be a comparison operator");
543     }
544     match nt {
545       nil_type => {
546         // We don't need to do actual comparisons for nil.
547         // () == () holds but () < () does not.
548         match op {
549           ast::BiEq | ast::BiLe | ast::BiGe => return C_bool(cx.ccx(), true),
550           ast::BiNe | ast::BiLt | ast::BiGt => return C_bool(cx.ccx(), false),
551           // refinements would be nice
552           _ => die(cx)
553         }
554       }
555       floating_point => {
556         let cmp = match op {
557           ast::BiEq => llvm::RealOEQ,
558           ast::BiNe => llvm::RealUNE,
559           ast::BiLt => llvm::RealOLT,
560           ast::BiLe => llvm::RealOLE,
561           ast::BiGt => llvm::RealOGT,
562           ast::BiGe => llvm::RealOGE,
563           _ => die(cx)
564         };
565         return FCmp(cx, cmp, lhs, rhs);
566       }
567       signed_int => {
568         let cmp = match op {
569           ast::BiEq => llvm::IntEQ,
570           ast::BiNe => llvm::IntNE,
571           ast::BiLt => llvm::IntSLT,
572           ast::BiLe => llvm::IntSLE,
573           ast::BiGt => llvm::IntSGT,
574           ast::BiGe => llvm::IntSGE,
575           _ => die(cx)
576         };
577         return ICmp(cx, cmp, lhs, rhs);
578       }
579       unsigned_int => {
580         let cmp = match op {
581           ast::BiEq => llvm::IntEQ,
582           ast::BiNe => llvm::IntNE,
583           ast::BiLt => llvm::IntULT,
584           ast::BiLe => llvm::IntULE,
585           ast::BiGt => llvm::IntUGT,
586           ast::BiGe => llvm::IntUGE,
587           _ => die(cx)
588         };
589         return ICmp(cx, cmp, lhs, rhs);
590       }
591     }
592 }
593
594 pub fn compare_simd_types(
595                     cx: &Block,
596                     lhs: ValueRef,
597                     rhs: ValueRef,
598                     t: ty::t,
599                     size: uint,
600                     op: ast::BinOp)
601                     -> ValueRef {
602     match ty::get(t).sty {
603         ty::ty_float(_) => {
604             // The comparison operators for floating point vectors are challenging.
605             // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
606             // then bitcast to a floating point vector, the result will be `-NaN`
607             // for each truth value. Because of this they are unsupported.
608             cx.sess().bug("compare_simd_types: comparison operators \
609                            not supported for floating point SIMD types")
610         },
611         ty::ty_uint(_) | ty::ty_int(_) => {
612             let cmp = match op {
613                 ast::BiEq => llvm::IntEQ,
614                 ast::BiNe => llvm::IntNE,
615                 ast::BiLt => llvm::IntSLT,
616                 ast::BiLe => llvm::IntSLE,
617                 ast::BiGt => llvm::IntSGT,
618                 ast::BiGe => llvm::IntSGE,
619                 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
620             };
621             let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
622             // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
623             // to get the correctly sized type. This will compile to a single instruction
624             // once the IR is converted to assembly if the SIMD instruction is supported
625             // by the target architecture.
626             SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
627         },
628         _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
629     }
630 }
631
632 pub type val_and_ty_fn<'r,'b> =
633     |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
634
635 // Iterates through the elements of a structural type.
636 pub fn iter_structural_ty<'r,
637                           'b>(
638                           cx: &'b Block<'b>,
639                           av: ValueRef,
640                           t: ty::t,
641                           f: val_and_ty_fn<'r,'b>)
642                           -> &'b Block<'b> {
643     let _icx = push_ctxt("iter_structural_ty");
644
645     fn iter_variant<'r,
646                     'b>(
647                     cx: &'b Block<'b>,
648                     repr: &adt::Repr,
649                     av: ValueRef,
650                     variant: &ty::VariantInfo,
651                     substs: &subst::Substs,
652                     f: val_and_ty_fn<'r,'b>)
653                     -> &'b Block<'b> {
654         let _icx = push_ctxt("iter_variant");
655         let tcx = cx.tcx();
656         let mut cx = cx;
657
658         for (i, &arg) in variant.args.iter().enumerate() {
659             cx = f(cx,
660                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
661                    arg.subst(tcx, substs));
662         }
663         return cx;
664     }
665
666     let mut cx = cx;
667     match ty::get(t).sty {
668       ty::ty_struct(..) => {
669           let repr = adt::represent_type(cx.ccx(), t);
670           expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
671               for (i, field_ty) in field_tys.iter().enumerate() {
672                   let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
673                   cx = f(cx, llfld_a, field_ty.mt.ty);
674               }
675           })
676       }
677       ty::ty_vec(_, Some(n)) => {
678         let unit_ty = ty::sequence_element_type(cx.tcx(), t);
679         let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
680         cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
681       }
682       ty::ty_tup(ref args) => {
683           let repr = adt::represent_type(cx.ccx(), t);
684           for (i, arg) in args.iter().enumerate() {
685               let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
686               cx = f(cx, llfld_a, *arg);
687           }
688       }
689       ty::ty_enum(tid, ref substs) => {
690           let fcx = cx.fcx;
691           let ccx = fcx.ccx;
692
693           let repr = adt::represent_type(ccx, t);
694           let variants = ty::enum_variants(ccx.tcx(), tid);
695           let n_variants = (*variants).len();
696
697           // NB: we must hit the discriminant first so that structural
698           // comparison know not to proceed when the discriminants differ.
699
700           match adt::trans_switch(cx, &*repr, av) {
701               (_match::single, None) => {
702                   cx = iter_variant(cx, &*repr, av, &**variants.get(0),
703                                     substs, f);
704               }
705               (_match::switch, Some(lldiscrim_a)) => {
706                   cx = f(cx, lldiscrim_a, ty::mk_int());
707                   let unr_cx = fcx.new_temp_block("enum-iter-unr");
708                   Unreachable(unr_cx);
709                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
710                                         n_variants);
711                   let next_cx = fcx.new_temp_block("enum-iter-next");
712
713                   for variant in (*variants).iter() {
714                       let variant_cx =
715                           fcx.new_temp_block(
716                               format!("enum-iter-variant-{}",
717                                       variant.disr_val.to_string().as_slice())
718                                      .as_slice());
719                       match adt::trans_case(cx, &*repr, variant.disr_val) {
720                           _match::single_result(r) => {
721                               AddCase(llswitch, r.val, variant_cx.llbb)
722                           }
723                           _ => ccx.sess().unimpl("value from adt::trans_case \
724                                                   in iter_structural_ty")
725                       }
726                       let variant_cx =
727                           iter_variant(variant_cx,
728                                        &*repr,
729                                        av,
730                                        &**variant,
731                                        substs,
732                                        |x,y,z| f(x,y,z));
733                       Br(variant_cx, next_cx.llbb);
734                   }
735                   cx = next_cx;
736               }
737               _ => ccx.sess().unimpl("value from adt::trans_switch \
738                                       in iter_structural_ty")
739           }
740       }
741       _ => cx.sess().unimpl("type in iter_structural_ty")
742     }
743     return cx;
744 }
745
746 pub fn cast_shift_expr_rhs<'a>(
747                            cx: &'a Block<'a>,
748                            op: ast::BinOp,
749                            lhs: ValueRef,
750                            rhs: ValueRef)
751                            -> ValueRef {
752     cast_shift_rhs(op, lhs, rhs,
753                    |a,b| Trunc(cx, a, b),
754                    |a,b| ZExt(cx, a, b))
755 }
756
757 pub fn cast_shift_const_rhs(op: ast::BinOp,
758                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
759     cast_shift_rhs(op, lhs, rhs,
760                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
761                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
762 }
763
764 pub fn cast_shift_rhs(op: ast::BinOp,
765                       lhs: ValueRef,
766                       rhs: ValueRef,
767                       trunc: |ValueRef, Type| -> ValueRef,
768                       zext: |ValueRef, Type| -> ValueRef)
769                       -> ValueRef {
770     // Shifts may have any size int on the rhs
771     unsafe {
772         if ast_util::is_shift_binop(op) {
773             let mut rhs_llty = val_ty(rhs);
774             let mut lhs_llty = val_ty(lhs);
775             if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
776             if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
777             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
778             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
779             if lhs_sz < rhs_sz {
780                 trunc(rhs, lhs_llty)
781             } else if lhs_sz > rhs_sz {
782                 // FIXME (#1877: If shifting by negative
783                 // values becomes not undefined then this is wrong.
784                 zext(rhs, lhs_llty)
785             } else {
786                 rhs
787             }
788         } else {
789             rhs
790         }
791     }
792 }
793
794 pub fn fail_if_zero_or_overflows<'a>(
795                     cx: &'a Block<'a>,
796                     span: Span,
797                     divrem: ast::BinOp,
798                     lhs: ValueRef,
799                     rhs: ValueRef,
800                     rhs_t: ty::t)
801                     -> &'a Block<'a> {
802     let (zero_text, overflow_text) = if divrem == ast::BiDiv {
803         ("attempted to divide by zero",
804          "attempted to divide with overflow")
805     } else {
806         ("attempted remainder with a divisor of zero",
807          "attempted remainder with overflow")
808     };
809     let (is_zero, is_signed) = match ty::get(rhs_t).sty {
810         ty::ty_int(t) => {
811             let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
812             (ICmp(cx, llvm::IntEQ, rhs, zero), true)
813         }
814         ty::ty_uint(t) => {
815             let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
816             (ICmp(cx, llvm::IntEQ, rhs, zero), false)
817         }
818         _ => {
819             cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
820                                   ty_to_string(cx.tcx(), rhs_t)).as_slice());
821         }
822     };
823     let bcx = with_cond(cx, is_zero, |bcx| {
824         controlflow::trans_fail(bcx, span, InternedString::new(zero_text))
825     });
826
827     // To quote LLVM's documentation for the sdiv instruction:
828     //
829     //      Division by zero leads to undefined behavior. Overflow also leads
830     //      to undefined behavior; this is a rare case, but can occur, for
831     //      example, by doing a 32-bit division of -2147483648 by -1.
832     //
833     // In order to avoid undefined behavior, we perform runtime checks for
834     // signed division/remainder which would trigger overflow. For unsigned
835     // integers, no action beyond checking for zero need be taken.
836     if is_signed {
837         let (llty, min) = match ty::get(rhs_t).sty {
838             ty::ty_int(t) => {
839                 let llty = Type::int_from_ty(cx.ccx(), t);
840                 let min = match t {
841                     ast::TyI if llty == Type::i32(cx.ccx()) => i32::MIN as u64,
842                     ast::TyI => i64::MIN as u64,
843                     ast::TyI8 => i8::MIN as u64,
844                     ast::TyI16 => i16::MIN as u64,
845                     ast::TyI32 => i32::MIN as u64,
846                     ast::TyI64 => i64::MIN as u64,
847                 };
848                 (llty, min)
849             }
850             _ => unreachable!(),
851         };
852         let minus_one = ICmp(bcx, llvm::IntEQ, rhs,
853                              C_integral(llty, -1, false));
854         with_cond(bcx, minus_one, |bcx| {
855             let is_min = ICmp(bcx, llvm::IntEQ, lhs,
856                               C_integral(llty, min, true));
857             with_cond(bcx, is_min, |bcx| {
858                 controlflow::trans_fail(bcx, span,
859                                         InternedString::new(overflow_text))
860             })
861         })
862     } else {
863         bcx
864     }
865 }
866
867 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
868     let name = csearch::get_symbol(&ccx.sess().cstore, did);
869     match ty::get(t).sty {
870         ty::ty_bare_fn(ref fn_ty) => {
871             match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
872                                        ccx.sess().targ_cfg.arch) {
873                 Some(Rust) => {
874                     get_extern_rust_fn(ccx, t, name.as_slice(), did)
875                 }
876                 Some(RustIntrinsic) => {
877                     ccx.sess().bug("unexpected intrinsic in trans_external_path")
878                 }
879                 Some(..) | None => {
880                     foreign::register_foreign_item_fn(ccx, fn_ty.abi, t,
881                                                       name.as_slice(), None)
882                 }
883             }
884         }
885         ty::ty_closure(_) => {
886             get_extern_rust_fn(ccx, t, name.as_slice(), did)
887         }
888         _ => {
889             let llty = type_of(ccx, t);
890             get_extern_const(&mut *ccx.externs.borrow_mut(),
891                              ccx.llmod,
892                              name.as_slice(),
893                              llty)
894         }
895     }
896 }
897
898 pub fn invoke<'a>(
899               bcx: &'a Block<'a>,
900               llfn: ValueRef,
901               llargs: Vec<ValueRef> ,
902               fn_ty: ty::t,
903               call_info: Option<NodeInfo>)
904               -> (ValueRef, &'a Block<'a>) {
905     let _icx = push_ctxt("invoke_");
906     if bcx.unreachable.get() {
907         return (C_null(Type::i8(bcx.ccx())), bcx);
908     }
909
910     let attributes = get_fn_llvm_attributes(bcx.ccx(), fn_ty);
911
912     match bcx.opt_node_id {
913         None => {
914             debug!("invoke at ???");
915         }
916         Some(id) => {
917             debug!("invoke at {}", bcx.tcx().map.node_to_string(id));
918         }
919     }
920
921     if need_invoke(bcx) {
922         debug!("invoking {} at {}", llfn, bcx.llbb);
923         for &llarg in llargs.iter() {
924             debug!("arg: {}", llarg);
925         }
926         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
927         let landing_pad = bcx.fcx.get_landing_pad();
928
929         match call_info {
930             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
931             None => debuginfo::clear_source_location(bcx.fcx)
932         };
933
934         let llresult = Invoke(bcx,
935                               llfn,
936                               llargs.as_slice(),
937                               normal_bcx.llbb,
938                               landing_pad,
939                               attributes.as_slice());
940         return (llresult, normal_bcx);
941     } else {
942         debug!("calling {} at {}", llfn, bcx.llbb);
943         for &llarg in llargs.iter() {
944             debug!("arg: {}", llarg);
945         }
946
947         match call_info {
948             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
949             None => debuginfo::clear_source_location(bcx.fcx)
950         };
951
952         let llresult = Call(bcx, llfn, llargs.as_slice(), attributes.as_slice());
953         return (llresult, bcx);
954     }
955 }
956
957 pub fn need_invoke(bcx: &Block) -> bool {
958     if bcx.sess().no_landing_pads() {
959         return false;
960     }
961
962     // Avoid using invoke if we are already inside a landing pad.
963     if bcx.is_lpad {
964         return false;
965     }
966
967     bcx.fcx.needs_invoke()
968 }
969
970 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
971     let _icx = push_ctxt("load_if_immediate");
972     if type_is_immediate(cx.ccx(), t) { return load_ty(cx, v, t); }
973     return v;
974 }
975
976 pub fn load_ty(cx: &Block, ptr: ValueRef, t: ty::t) -> ValueRef {
977     /*!
978      * Helper for loading values from memory. Does the necessary conversion if
979      * the in-memory type differs from the type used for SSA values. Also
980      * handles various special cases where the type gives us better information
981      * about what we are loading.
982      */
983     if type_is_zero_size(cx.ccx(), t) {
984         C_undef(type_of::type_of(cx.ccx(), t))
985     } else if ty::type_is_bool(t) {
986         Trunc(cx, LoadRangeAssert(cx, ptr, 0, 2, llvm::False), Type::i1(cx.ccx()))
987     } else if ty::type_is_char(t) {
988         // a char is a unicode codepoint, and so takes values from 0
989         // to 0x10FFFF inclusive only.
990         LoadRangeAssert(cx, ptr, 0, 0x10FFFF + 1, llvm::False)
991     } else {
992         Load(cx, ptr)
993     }
994 }
995
996 pub fn store_ty(cx: &Block, v: ValueRef, dst: ValueRef, t: ty::t) {
997     /*!
998      * Helper for storing values in memory. Does the necessary conversion if
999      * the in-memory type differs from the type used for SSA values.
1000      */
1001     if ty::type_is_bool(t) {
1002         Store(cx, ZExt(cx, v, Type::i8(cx.ccx())), dst);
1003     } else {
1004         Store(cx, v, dst);
1005     };
1006 }
1007
1008 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1009     match local.pat.node {
1010         ast::PatWild => true, _ => false
1011     }
1012 }
1013
1014 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1015                   -> &'a Block<'a> {
1016     debug!("init_local(bcx={}, local.id={:?})", bcx.to_str(), local.id);
1017     let _indenter = indenter();
1018     let _icx = push_ctxt("init_local");
1019     _match::store_local(bcx, local)
1020 }
1021
1022 pub fn raw_block<'a>(
1023                  fcx: &'a FunctionContext<'a>,
1024                  is_lpad: bool,
1025                  llbb: BasicBlockRef)
1026                  -> &'a Block<'a> {
1027     Block::new(llbb, is_lpad, None, fcx)
1028 }
1029
1030 pub fn with_cond<'a>(
1031                  bcx: &'a Block<'a>,
1032                  val: ValueRef,
1033                  f: |&'a Block<'a>| -> &'a Block<'a>)
1034                  -> &'a Block<'a> {
1035     let _icx = push_ctxt("with_cond");
1036     let fcx = bcx.fcx;
1037     let next_cx = fcx.new_temp_block("next");
1038     let cond_cx = fcx.new_temp_block("cond");
1039     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1040     let after_cx = f(cond_cx);
1041     if !after_cx.terminated.get() {
1042         Br(after_cx, next_cx.llbb);
1043     }
1044     next_cx
1045 }
1046
1047 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1048     let _icx = push_ctxt("call_memcpy");
1049     let ccx = cx.ccx();
1050     let key = match ccx.sess().targ_cfg.arch {
1051         X86 | Arm | Mips | Mipsel => "llvm.memcpy.p0i8.p0i8.i32",
1052         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1053     };
1054     let memcpy = ccx.get_intrinsic(&key);
1055     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1056     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1057     let size = IntCast(cx, n_bytes, ccx.int_type);
1058     let align = C_i32(ccx, align as i32);
1059     let volatile = C_bool(ccx, false);
1060     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1061 }
1062
1063 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1064     let _icx = push_ctxt("memcpy_ty");
1065     let ccx = bcx.ccx();
1066     if ty::type_is_structural(t) {
1067         let llty = type_of::type_of(ccx, t);
1068         let llsz = llsize_of(ccx, llty);
1069         let llalign = llalign_of_min(ccx, llty);
1070         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1071     } else {
1072         Store(bcx, Load(bcx, src), dst);
1073     }
1074 }
1075
1076 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1077     if cx.unreachable.get() { return; }
1078     let _icx = push_ctxt("zero_mem");
1079     let bcx = cx;
1080     let ccx = cx.ccx();
1081     let llty = type_of::type_of(ccx, t);
1082     memzero(&B(bcx), llptr, llty);
1083 }
1084
1085 // Always use this function instead of storing a zero constant to the memory
1086 // in question. If you store a zero constant, LLVM will drown in vreg
1087 // allocation for large data structures, and the generated code will be
1088 // awful. (A telltale sign of this is large quantities of
1089 // `mov [byte ptr foo],0` in the generated code.)
1090 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1091     let _icx = push_ctxt("memzero");
1092     let ccx = b.ccx;
1093
1094     let intrinsic_key = match ccx.sess().targ_cfg.arch {
1095         X86 | Arm | Mips | Mipsel => "llvm.memset.p0i8.i32",
1096         X86_64 => "llvm.memset.p0i8.i64"
1097     };
1098
1099     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1100     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1101     let llzeroval = C_u8(ccx, 0);
1102     let size = machine::llsize_of(ccx, ty);
1103     let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1104     let volatile = C_bool(ccx, false);
1105     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1106 }
1107
1108 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1109     let _icx = push_ctxt("alloc_ty");
1110     let ccx = bcx.ccx();
1111     let ty = type_of::type_of(ccx, t);
1112     assert!(!ty::type_has_params(t));
1113     let val = alloca(bcx, ty, name);
1114     return val;
1115 }
1116
1117 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1118     alloca_maybe_zeroed(cx, ty, name, false)
1119 }
1120
1121 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1122     let _icx = push_ctxt("alloca");
1123     if cx.unreachable.get() {
1124         unsafe {
1125             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1126         }
1127     }
1128     debuginfo::clear_source_location(cx.fcx);
1129     let p = Alloca(cx, ty, name);
1130     if zero {
1131         let b = cx.fcx.ccx.builder();
1132         b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1133         memzero(&b, p, ty);
1134     }
1135     p
1136 }
1137
1138 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1139     let _icx = push_ctxt("arrayalloca");
1140     if cx.unreachable.get() {
1141         unsafe {
1142             return llvm::LLVMGetUndef(ty.to_ref());
1143         }
1144     }
1145     debuginfo::clear_source_location(cx.fcx);
1146     return ArrayAlloca(cx, ty, v);
1147 }
1148
1149 // Creates and returns space for, or returns the argument representing, the
1150 // slot where the return value of the function must go.
1151 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1152                            -> ValueRef {
1153     unsafe {
1154         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1155             llvm::LLVMGetParam(fcx.llfn, 0)
1156         } else {
1157             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1158             AllocaFcx(fcx, lloutputtype, "__make_return_pointer")
1159         }
1160     }
1161 }
1162
1163 // NB: must keep 4 fns in sync:
1164 //
1165 //  - type_of_fn
1166 //  - create_datums_for_fn_args.
1167 //  - new_fn_ctxt
1168 //  - trans_args
1169 //
1170 // Be warned! You must call `init_function` before doing anything with the
1171 // returned function context.
1172 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1173                        llfndecl: ValueRef,
1174                        id: ast::NodeId,
1175                        has_env: bool,
1176                        output_type: ty::t,
1177                        param_substs: &'a param_substs,
1178                        sp: Option<Span>,
1179                        block_arena: &'a TypedArena<Block<'a>>)
1180                        -> FunctionContext<'a> {
1181     param_substs.validate();
1182
1183     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1184            if id == -1 {
1185                "".to_string()
1186            } else {
1187                ccx.tcx.map.path_to_string(id).to_string()
1188            },
1189            id, param_substs.repr(ccx.tcx()));
1190
1191     let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1192     let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1193     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1194
1195     let mut fcx = FunctionContext {
1196           llfn: llfndecl,
1197           llenv: None,
1198           llretptr: Cell::new(None),
1199           alloca_insert_pt: Cell::new(None),
1200           llreturn: Cell::new(None),
1201           personality: Cell::new(None),
1202           caller_expects_out_pointer: uses_outptr,
1203           llargs: RefCell::new(NodeMap::new()),
1204           lllocals: RefCell::new(NodeMap::new()),
1205           llupvars: RefCell::new(NodeMap::new()),
1206           id: id,
1207           param_substs: param_substs,
1208           span: sp,
1209           block_arena: block_arena,
1210           ccx: ccx,
1211           debug_context: debug_context,
1212           scopes: RefCell::new(Vec::new())
1213     };
1214
1215     if has_env {
1216         fcx.llenv = Some(unsafe {
1217             llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1218         });
1219     }
1220
1221     fcx
1222 }
1223
1224 /// Performs setup on a newly created function, creating the entry scope block
1225 /// and allocating space for the return pointer.
1226 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1227                          skip_retptr: bool,
1228                          output_type: ty::t) -> &'a Block<'a> {
1229     let entry_bcx = fcx.new_temp_block("entry-block");
1230
1231     // Use a dummy instruction as the insertion point for all allocas.
1232     // This is later removed in FunctionContext::cleanup.
1233     fcx.alloca_insert_pt.set(Some(unsafe {
1234         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1235         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1236     }));
1237
1238     // This shouldn't need to recompute the return type,
1239     // as new_fn_ctxt did it already.
1240     let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1241
1242     if !return_type_is_void(fcx.ccx, substd_output_type) {
1243         // If the function returns nil/bot, there is no real return
1244         // value, so do not set `llretptr`.
1245         if !skip_retptr || fcx.caller_expects_out_pointer {
1246             // Otherwise, we normally allocate the llretptr, unless we
1247             // have been instructed to skip it for immediate return
1248             // values.
1249             fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1250         }
1251     }
1252
1253     entry_bcx
1254 }
1255
1256 // NB: must keep 4 fns in sync:
1257 //
1258 //  - type_of_fn
1259 //  - create_datums_for_fn_args.
1260 //  - new_fn_ctxt
1261 //  - trans_args
1262
1263 pub fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1264     use middle::trans::datum::{ByRef, ByValue};
1265
1266     datum::Rvalue {
1267         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1268     }
1269 }
1270
1271 // work around bizarre resolve errors
1272 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1273 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1274
1275 // create_datums_for_fn_args: creates rvalue datums for each of the
1276 // incoming function arguments. These will later be stored into
1277 // appropriate lvalue datums.
1278 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1279                                  arg_tys: &[ty::t])
1280                                  -> Vec<RvalueDatum> {
1281     let _icx = push_ctxt("create_datums_for_fn_args");
1282
1283     // Return an array wrapping the ValueRefs that we get from
1284     // llvm::LLVMGetParam for each argument into datums.
1285     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1286         let llarg = unsafe {
1287             llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1288         };
1289         datum::Datum::new(llarg, arg_ty, arg_kind(fcx, arg_ty))
1290     }).collect()
1291 }
1292
1293 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1294                             arg_scope: cleanup::CustomScopeIndex,
1295                             bcx: &'a Block<'a>,
1296                             args: &[ast::Arg],
1297                             arg_datums: Vec<RvalueDatum> )
1298                             -> &'a Block<'a> {
1299     debug!("copy_args_to_allocas");
1300
1301     let _icx = push_ctxt("copy_args_to_allocas");
1302     let mut bcx = bcx;
1303
1304     let arg_scope_id = cleanup::CustomScope(arg_scope);
1305
1306     for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1307         // For certain mode/type combinations, the raw llarg values are passed
1308         // by value.  However, within the fn body itself, we want to always
1309         // have all locals and arguments be by-ref so that we can cancel the
1310         // cleanup and for better interaction with LLVM's debug info.  So, if
1311         // the argument would be passed by value, we store it into an alloca.
1312         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1313         // the event it's not truly needed.
1314
1315         bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1316
1317         if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1318             debuginfo::create_argument_metadata(bcx, &args[i]);
1319         }
1320     }
1321
1322     bcx
1323 }
1324
1325 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1326 // and builds the return block.
1327 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1328                      last_bcx: &'a Block<'a>,
1329                      retty: ty::t) {
1330     let _icx = push_ctxt("finish_fn");
1331
1332     // This shouldn't need to recompute the return type,
1333     // as new_fn_ctxt did it already.
1334     let substd_retty = retty.substp(fcx.ccx.tcx(), fcx.param_substs);
1335
1336     let ret_cx = match fcx.llreturn.get() {
1337         Some(llreturn) => {
1338             if !last_bcx.terminated.get() {
1339                 Br(last_bcx, llreturn);
1340             }
1341             raw_block(fcx, false, llreturn)
1342         }
1343         None => last_bcx
1344     };
1345     build_return_block(fcx, ret_cx, substd_retty);
1346     debuginfo::clear_source_location(fcx);
1347     fcx.cleanup();
1348 }
1349
1350 // Builds the return block for a function.
1351 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block, retty: ty::t) {
1352     // Return the value if this function immediate; otherwise, return void.
1353     if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1354         return RetVoid(ret_cx);
1355     }
1356
1357     let retptr = Value(fcx.llretptr.get().unwrap());
1358     let retval = match retptr.get_dominating_store(ret_cx) {
1359         // If there's only a single store to the ret slot, we can directly return
1360         // the value that was stored and omit the store and the alloca
1361         Some(s) => {
1362             let retval = s.get_operand(0).unwrap().get();
1363             s.erase_from_parent();
1364
1365             if retptr.has_no_uses() {
1366                 retptr.erase_from_parent();
1367             }
1368
1369             if ty::type_is_bool(retty) {
1370                 Trunc(ret_cx, retval, Type::i1(fcx.ccx))
1371             } else {
1372                 retval
1373             }
1374         }
1375         // Otherwise, load the return value from the ret slot
1376         None => load_ty(ret_cx, fcx.llretptr.get().unwrap(), retty)
1377     };
1378
1379     Ret(ret_cx, retval);
1380 }
1381
1382 // trans_closure: Builds an LLVM function out of a source function.
1383 // If the function closes over its environment a closure will be
1384 // returned.
1385 pub fn trans_closure(ccx: &CrateContext,
1386                      decl: &ast::FnDecl,
1387                      body: &ast::Block,
1388                      llfndecl: ValueRef,
1389                      param_substs: &param_substs,
1390                      id: ast::NodeId,
1391                      _attributes: &[ast::Attribute],
1392                      output_type: ty::t,
1393                      maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1394     ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1395
1396     let _icx = push_ctxt("trans_closure");
1397     set_uwtable(llfndecl);
1398
1399     debug!("trans_closure(..., param_substs={})",
1400            param_substs.repr(ccx.tcx()));
1401
1402     let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1403         ty::ty_closure(_) => true,
1404         _ => false
1405     };
1406
1407     let arena = TypedArena::new();
1408     let fcx = new_fn_ctxt(ccx,
1409                           llfndecl,
1410                           id,
1411                           has_env,
1412                           output_type,
1413                           param_substs,
1414                           Some(body.span),
1415                           &arena);
1416     let mut bcx = init_function(&fcx, false, output_type);
1417
1418     // cleanup scope for the incoming arguments
1419     let arg_scope = fcx.push_custom_cleanup_scope();
1420
1421     let block_ty = node_id_type(bcx, body.id);
1422
1423     // Set up arguments to the function.
1424     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1425     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1426
1427     bcx = copy_args_to_allocas(&fcx,
1428                                arg_scope,
1429                                bcx,
1430                                decl.inputs.as_slice(),
1431                                arg_datums);
1432
1433     bcx = maybe_load_env(bcx);
1434
1435     // Up until here, IR instructions for this function have explicitly not been annotated with
1436     // source code location, so we don't step into call setup code. From here on, source location
1437     // emitting should be enabled.
1438     debuginfo::start_emitting_source_locations(&fcx);
1439
1440     let dest = match fcx.llretptr.get() {
1441         Some(e) => {expr::SaveIn(e)}
1442         None => {
1443             assert!(type_is_zero_size(bcx.ccx(), block_ty))
1444             expr::Ignore
1445         }
1446     };
1447
1448     // This call to trans_block is the place where we bridge between
1449     // translation calls that don't have a return value (trans_crate,
1450     // trans_mod, trans_item, et cetera) and those that do
1451     // (trans_block, trans_expr, et cetera).
1452     bcx = controlflow::trans_block(bcx, body, dest);
1453
1454     match fcx.llreturn.get() {
1455         Some(_) => {
1456             Br(bcx, fcx.return_exit_block());
1457             fcx.pop_custom_cleanup_scope(arg_scope);
1458         }
1459         None => {
1460             // Microoptimization writ large: avoid creating a separate
1461             // llreturn basic block
1462             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1463         }
1464     };
1465
1466     // Put return block after all other blocks.
1467     // This somewhat improves single-stepping experience in debugger.
1468     unsafe {
1469         let llreturn = fcx.llreturn.get();
1470         for &llreturn in llreturn.iter() {
1471             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1472         }
1473     }
1474
1475     // Insert the mandatory first few basic blocks before lltop.
1476     finish_fn(&fcx, bcx, output_type);
1477 }
1478
1479 // trans_fn: creates an LLVM function corresponding to a source language
1480 // function.
1481 pub fn trans_fn(ccx: &CrateContext,
1482                 decl: &ast::FnDecl,
1483                 body: &ast::Block,
1484                 llfndecl: ValueRef,
1485                 param_substs: &param_substs,
1486                 id: ast::NodeId,
1487                 attrs: &[ast::Attribute]) {
1488     let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_string(id).to_string());
1489     debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx()));
1490     let _icx = push_ctxt("trans_fn");
1491     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1492     trans_closure(ccx, decl, body, llfndecl,
1493                   param_substs, id, attrs, output_type, |bcx| bcx);
1494 }
1495
1496 pub fn trans_enum_variant(ccx: &CrateContext,
1497                           _enum_id: ast::NodeId,
1498                           variant: &ast::Variant,
1499                           _args: &[ast::VariantArg],
1500                           disr: ty::Disr,
1501                           param_substs: &param_substs,
1502                           llfndecl: ValueRef) {
1503     let _icx = push_ctxt("trans_enum_variant");
1504
1505     trans_enum_variant_or_tuple_like_struct(
1506         ccx,
1507         variant.node.id,
1508         disr,
1509         param_substs,
1510         llfndecl);
1511 }
1512
1513 pub fn trans_tuple_struct(ccx: &CrateContext,
1514                           _fields: &[ast::StructField],
1515                           ctor_id: ast::NodeId,
1516                           param_substs: &param_substs,
1517                           llfndecl: ValueRef) {
1518     let _icx = push_ctxt("trans_tuple_struct");
1519
1520     trans_enum_variant_or_tuple_like_struct(
1521         ccx,
1522         ctor_id,
1523         0,
1524         param_substs,
1525         llfndecl);
1526 }
1527
1528 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1529                                            ctor_id: ast::NodeId,
1530                                            disr: ty::Disr,
1531                                            param_substs: &param_substs,
1532                                            llfndecl: ValueRef) {
1533     let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1534     let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1535
1536     let result_ty = match ty::get(ctor_ty).sty {
1537         ty::ty_bare_fn(ref bft) => bft.sig.output,
1538         _ => ccx.sess().bug(
1539             format!("trans_enum_variant_or_tuple_like_struct: \
1540                      unexpected ctor return type {}",
1541                     ty_to_string(ccx.tcx(), ctor_ty)).as_slice())
1542     };
1543
1544     let arena = TypedArena::new();
1545     let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1546                           param_substs, None, &arena);
1547     let bcx = init_function(&fcx, false, result_ty);
1548
1549     let arg_tys = ty::ty_fn_args(ctor_ty);
1550
1551     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1552
1553     if !type_is_zero_size(fcx.ccx, result_ty) {
1554         let repr = adt::represent_type(ccx, result_ty);
1555         adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1556         for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1557             let lldestptr = adt::trans_field_ptr(bcx,
1558                                                  &*repr,
1559                                                  fcx.llretptr.get().unwrap(),
1560                                                  disr,
1561                                                  i);
1562             arg_datum.store_to(bcx, lldestptr);
1563         }
1564     }
1565
1566     finish_fn(&fcx, bcx, result_ty);
1567 }
1568
1569 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1570                   sp: Span, id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1571                   i: &mut uint) {
1572     for variant in enum_definition.variants.iter() {
1573         let disr_val = vi[*i].disr_val;
1574         *i += 1;
1575
1576         match variant.node.kind {
1577             ast::TupleVariantKind(ref args) if args.len() > 0 => {
1578                 let llfn = get_item_val(ccx, variant.node.id);
1579                 trans_enum_variant(ccx, id, &**variant, args.as_slice(),
1580                                    disr_val, &param_substs::empty(), llfn);
1581             }
1582             ast::TupleVariantKind(_) => {
1583                 // Nothing to do.
1584             }
1585             ast::StructVariantKind(struct_def) => {
1586                 trans_struct_def(ccx, struct_def);
1587             }
1588         }
1589     }
1590
1591     enum_variant_size_lint(ccx, enum_definition, sp, id);
1592 }
1593
1594 fn enum_variant_size_lint(ccx: &CrateContext, enum_def: &ast::EnumDef, sp: Span, id: ast::NodeId) {
1595     let mut sizes = Vec::new(); // does no allocation if no pushes, thankfully
1596
1597     let levels = ccx.tcx.node_lint_levels.borrow();
1598     let lint_id = lint::LintId::of(lint::builtin::VARIANT_SIZE_DIFFERENCE);
1599     let lvlsrc = match levels.find(&(id, lint_id)) {
1600         None | Some(&(lint::Allow, _)) => return,
1601         Some(&lvlsrc) => lvlsrc,
1602     };
1603
1604     let avar = adt::represent_type(ccx, ty::node_id_to_type(ccx.tcx(), id));
1605     match *avar {
1606         adt::General(_, ref variants) => {
1607             for var in variants.iter() {
1608                 let mut size = 0;
1609                 for field in var.fields.iter().skip(1) {
1610                     // skip the discriminant
1611                     size += llsize_of_real(ccx, sizing_type_of(ccx, *field));
1612                 }
1613                 sizes.push(size);
1614             }
1615         },
1616         _ => { /* its size is either constant or unimportant */ }
1617     }
1618
1619     let (largest, slargest, largest_index) = sizes.iter().enumerate().fold((0, 0, 0),
1620         |(l, s, li), (idx, &size)|
1621             if size > l {
1622                 (size, l, idx)
1623             } else if size > s {
1624                 (l, size, li)
1625             } else {
1626                 (l, s, li)
1627             }
1628     );
1629
1630     // we only warn if the largest variant is at least thrice as large as
1631     // the second-largest.
1632     if largest > slargest * 3 && slargest > 0 {
1633         // Use lint::raw_emit_lint rather than sess.add_lint because the lint-printing
1634         // pass for the latter already ran.
1635         lint::raw_emit_lint(&ccx.tcx().sess, lint::builtin::VARIANT_SIZE_DIFFERENCE,
1636                             lvlsrc, Some(sp),
1637                             format!("enum variant is more than three times larger \
1638                                      ({} bytes) than the next largest (ignoring padding)",
1639                                     largest).as_slice());
1640
1641         ccx.sess().span_note(enum_def.variants.get(largest_index).span,
1642                              "this variant is the largest");
1643     }
1644 }
1645
1646 pub struct TransItemVisitor<'a> {
1647     pub ccx: &'a CrateContext,
1648 }
1649
1650 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1651     fn visit_item(&mut self, i: &ast::Item, _:()) {
1652         trans_item(self.ccx, i);
1653     }
1654 }
1655
1656 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1657     let _icx = push_ctxt("trans_item");
1658     match item.node {
1659       ast::ItemFn(ref decl, _fn_style, abi, ref generics, ref body) => {
1660         if abi != Rust  {
1661             let llfndecl = get_item_val(ccx, item.id);
1662             foreign::trans_rust_fn_with_foreign_abi(
1663                 ccx, &**decl, &**body, item.attrs.as_slice(), llfndecl, item.id);
1664         } else if !generics.is_type_parameterized() {
1665             let llfn = get_item_val(ccx, item.id);
1666             trans_fn(ccx,
1667                      &**decl,
1668                      &**body,
1669                      llfn,
1670                      &param_substs::empty(),
1671                      item.id,
1672                      item.attrs.as_slice());
1673         } else {
1674             // Be sure to travel more than just one layer deep to catch nested
1675             // items in blocks and such.
1676             let mut v = TransItemVisitor{ ccx: ccx };
1677             v.visit_block(&**body, ());
1678         }
1679       }
1680       ast::ItemImpl(ref generics, _, _, ref ms) => {
1681         meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1682       }
1683       ast::ItemMod(ref m) => {
1684         trans_mod(ccx, m);
1685       }
1686       ast::ItemEnum(ref enum_definition, ref generics) => {
1687         if !generics.is_type_parameterized() {
1688             let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1689             let mut i = 0;
1690             trans_enum_def(ccx, enum_definition, item.span, item.id, vi.as_slice(), &mut i);
1691         }
1692       }
1693       ast::ItemStatic(_, m, ref expr) => {
1694           // Recurse on the expression to catch items in blocks
1695           let mut v = TransItemVisitor{ ccx: ccx };
1696           v.visit_expr(&**expr, ());
1697           consts::trans_const(ccx, m, item.id);
1698           // Do static_assert checking. It can't really be done much earlier
1699           // because we need to get the value of the bool out of LLVM
1700           if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1701               if m == ast::MutMutable {
1702                   ccx.sess().span_fatal(expr.span,
1703                                         "cannot have static_assert on a mutable \
1704                                          static");
1705               }
1706
1707               let v = ccx.const_values.borrow().get_copy(&item.id);
1708               unsafe {
1709                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1710                       ccx.sess().span_fatal(expr.span, "static assertion failed");
1711                   }
1712               }
1713           }
1714       },
1715       ast::ItemForeignMod(ref foreign_mod) => {
1716         foreign::trans_foreign_mod(ccx, foreign_mod);
1717       }
1718       ast::ItemStruct(struct_def, ref generics) => {
1719         if !generics.is_type_parameterized() {
1720             trans_struct_def(ccx, struct_def);
1721         }
1722       }
1723       ast::ItemTrait(..) => {
1724         // Inside of this trait definition, we won't be actually translating any
1725         // functions, but the trait still needs to be walked. Otherwise default
1726         // methods with items will not get translated and will cause ICE's when
1727         // metadata time comes around.
1728         let mut v = TransItemVisitor{ ccx: ccx };
1729         visit::walk_item(&mut v, item, ());
1730       }
1731       _ => {/* fall through */ }
1732     }
1733 }
1734
1735 pub fn trans_struct_def(ccx: &CrateContext, struct_def: Gc<ast::StructDef>) {
1736     // If this is a tuple-like struct, translate the constructor.
1737     match struct_def.ctor_id {
1738         // We only need to translate a constructor if there are fields;
1739         // otherwise this is a unit-like struct.
1740         Some(ctor_id) if struct_def.fields.len() > 0 => {
1741             let llfndecl = get_item_val(ccx, ctor_id);
1742             trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1743                                ctor_id, &param_substs::empty(), llfndecl);
1744         }
1745         Some(_) | None => {}
1746     }
1747 }
1748
1749 // Translate a module. Doing this amounts to translating the items in the
1750 // module; there ends up being no artifact (aside from linkage names) of
1751 // separate modules in the compiled program.  That's because modules exist
1752 // only as a convenience for humans working with the code, to organize names
1753 // and control visibility.
1754 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1755     let _icx = push_ctxt("trans_mod");
1756     for item in m.items.iter() {
1757         trans_item(ccx, &**item);
1758     }
1759 }
1760
1761 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: String, node_id: ast::NodeId,
1762                       llfn: ValueRef) {
1763     ccx.item_symbols.borrow_mut().insert(node_id, sym);
1764
1765     if !ccx.reachable.contains(&node_id) {
1766         llvm::SetLinkage(llfn, llvm::InternalLinkage);
1767     }
1768
1769     // The stack exhaustion lang item shouldn't have a split stack because
1770     // otherwise it would continue to be exhausted (bad), and both it and the
1771     // eh_personality functions need to be externally linkable.
1772     let def = ast_util::local_def(node_id);
1773     if ccx.tcx.lang_items.stack_exhausted() == Some(def) {
1774         unset_split_stack(llfn);
1775         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1776     }
1777     if ccx.tcx.lang_items.eh_personality() == Some(def) {
1778         llvm::SetLinkage(llfn, llvm::ExternalLinkage);
1779     }
1780
1781
1782     if is_entry_fn(ccx.sess(), node_id) {
1783         create_entry_wrapper(ccx, sp, llfn);
1784     }
1785 }
1786
1787 fn register_fn(ccx: &CrateContext,
1788                sp: Span,
1789                sym: String,
1790                node_id: ast::NodeId,
1791                node_type: ty::t)
1792                -> ValueRef {
1793     match ty::get(node_type).sty {
1794         ty::ty_bare_fn(ref f) => {
1795             assert!(f.abi == Rust);
1796         }
1797         _ => fail!("expected bare rust fn")
1798     };
1799
1800     let llfn = decl_rust_fn(ccx, node_type, sym.as_slice());
1801     finish_register_fn(ccx, sp, sym, node_id, llfn);
1802     llfn
1803 }
1804
1805 pub fn get_fn_llvm_attributes(ccx: &CrateContext, fn_ty: ty::t) -> Vec<(uint, u64)> {
1806     use middle::ty::{BrAnon, ReLateBound};
1807
1808     let (fn_sig, has_env) = match ty::get(fn_ty).sty {
1809         ty::ty_closure(ref f) => (f.sig.clone(), true),
1810         ty::ty_bare_fn(ref f) => (f.sig.clone(), false),
1811         _ => fail!("expected closure or function.")
1812     };
1813
1814     // Since index 0 is the return value of the llvm func, we start
1815     // at either 1 or 2 depending on whether there's an env slot or not
1816     let mut first_arg_offset = if has_env { 2 } else { 1 };
1817     let mut attrs = Vec::new();
1818     let ret_ty = fn_sig.output;
1819
1820     // A function pointer is called without the declaration
1821     // available, so we have to apply any attributes with ABI
1822     // implications directly to the call instruction. Right now,
1823     // the only attribute we need to worry about is `sret`.
1824     if type_of::return_uses_outptr(ccx, ret_ty) {
1825         attrs.push((1, llvm::StructRetAttribute as u64));
1826
1827         // The outptr can be noalias and nocapture because it's entirely
1828         // invisible to the program. We can also mark it as nonnull
1829         attrs.push((1, llvm::NoAliasAttribute as u64));
1830         attrs.push((1, llvm::NoCaptureAttribute as u64));
1831         attrs.push((1, llvm::NonNullAttribute as u64));
1832
1833         // Add one more since there's an outptr
1834         first_arg_offset += 1;
1835     } else {
1836         // The `noalias` attribute on the return value is useful to a
1837         // function ptr caller.
1838         match ty::get(ret_ty).sty {
1839             // `~` pointer return values never alias because ownership
1840             // is transferred
1841             ty::ty_uniq(it)  if match ty::get(it).sty {
1842                 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
1843             } => {}
1844             ty::ty_uniq(_) => {
1845                 attrs.push((llvm::ReturnIndex as uint, llvm::NoAliasAttribute as u64));
1846             }
1847             _ => {}
1848         }
1849
1850         // We can also mark the return value as `nonnull` in certain cases
1851         match ty::get(ret_ty).sty {
1852             // These are not really pointers but pairs, (pointer, len)
1853             ty::ty_uniq(it) |
1854             ty::ty_rptr(_, ty::mt { ty: it, .. }) if match ty::get(it).sty {
1855                 ty::ty_str | ty::ty_vec(..) | ty::ty_trait(..) => true, _ => false
1856             } => {}
1857             ty::ty_uniq(_) | ty::ty_rptr(_, _) => {
1858                 attrs.push((llvm::ReturnIndex as uint, llvm::NonNullAttribute as u64));
1859             }
1860             _ => {}
1861         }
1862
1863         match ty::get(ret_ty).sty {
1864             ty::ty_bool => {
1865                 attrs.push((llvm::ReturnIndex as uint, llvm::ZExtAttribute as u64));
1866             }
1867             _ => {}
1868         }
1869     }
1870
1871     for (idx, &t) in fn_sig.inputs.iter().enumerate().map(|(i, v)| (i + first_arg_offset, v)) {
1872         match ty::get(t).sty {
1873             // this needs to be first to prevent fat pointers from falling through
1874             _ if !type_is_immediate(ccx, t) => {
1875                 // For non-immediate arguments the callee gets its own copy of
1876                 // the value on the stack, so there are no aliases. It's also
1877                 // program-invisible so can't possibly capture
1878                 attrs.push((idx, llvm::NoAliasAttribute as u64));
1879                 attrs.push((idx, llvm::NoCaptureAttribute as u64));
1880                 attrs.push((idx, llvm::NonNullAttribute as u64));
1881             }
1882             ty::ty_bool => {
1883                 attrs.push((idx, llvm::ZExtAttribute as u64));
1884             }
1885             // `~` pointer parameters never alias because ownership is transferred
1886             ty::ty_uniq(_) => {
1887                 attrs.push((idx, llvm::NoAliasAttribute as u64));
1888                 attrs.push((idx, llvm::NonNullAttribute as u64));
1889             }
1890             // `&mut` pointer parameters never alias other parameters, or mutable global data
1891             ty::ty_rptr(b, mt) if mt.mutbl == ast::MutMutable => {
1892                 attrs.push((idx, llvm::NoAliasAttribute as u64));
1893                 attrs.push((idx, llvm::NonNullAttribute as u64));
1894                 match b {
1895                     ReLateBound(_, BrAnon(_)) => {
1896                         attrs.push((idx, llvm::NoCaptureAttribute as u64));
1897                     }
1898                     _ => {}
1899                 }
1900             }
1901             // When a reference in an argument has no named lifetime, it's impossible for that
1902             // reference to escape this function (returned or stored beyond the call by a closure).
1903             ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
1904                 attrs.push((idx, llvm::NoCaptureAttribute as u64));
1905                 attrs.push((idx, llvm::NonNullAttribute as u64));
1906             }
1907             // & pointer parameters are never null
1908             ty::ty_rptr(_, _) => {
1909                 attrs.push((idx, llvm::NonNullAttribute as u64));
1910             }
1911             _ => ()
1912         }
1913     }
1914
1915     attrs
1916 }
1917
1918 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1919 pub fn register_fn_llvmty(ccx: &CrateContext,
1920                           sp: Span,
1921                           sym: String,
1922                           node_id: ast::NodeId,
1923                           cc: llvm::CallConv,
1924                           llfty: Type) -> ValueRef {
1925     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1926
1927     let llfn = decl_fn(ccx, sym.as_slice(), cc, llfty, ty::mk_nil());
1928     finish_register_fn(ccx, sp, sym, node_id, llfn);
1929     llfn
1930 }
1931
1932 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1933     match *sess.entry_fn.borrow() {
1934         Some((entry_id, _)) => node_id == entry_id,
1935         None => false
1936     }
1937 }
1938
1939 // Create a _rust_main(args: ~[str]) function which will be called from the
1940 // runtime rust_start function
1941 pub fn create_entry_wrapper(ccx: &CrateContext,
1942                            _sp: Span,
1943                            main_llfn: ValueRef) {
1944     let et = ccx.sess().entry_type.get().unwrap();
1945     match et {
1946         config::EntryMain => {
1947             create_entry_fn(ccx, main_llfn, true);
1948         }
1949         config::EntryStart => create_entry_fn(ccx, main_llfn, false),
1950         config::EntryNone => {}    // Do nothing.
1951     }
1952
1953     fn create_entry_fn(ccx: &CrateContext,
1954                        rust_main: ValueRef,
1955                        use_start_lang_item: bool) {
1956         let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1957                                &ccx.int_type);
1958
1959         let llfn = decl_cdecl_fn(ccx, "main", llfty, ty::mk_nil());
1960         let llbb = "top".with_c_str(|buf| {
1961             unsafe {
1962                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1963             }
1964         });
1965         let bld = ccx.builder.b;
1966         unsafe {
1967             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1968
1969             let (start_fn, args) = if use_start_lang_item {
1970                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1971                     Ok(id) => id,
1972                     Err(s) => { ccx.sess().fatal(s.as_slice()); }
1973                 };
1974                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1975                     get_item_val(ccx, start_def_id.node)
1976                 } else {
1977                     let start_fn_type = csearch::get_type(ccx.tcx(),
1978                                                           start_def_id).ty;
1979                     trans_external_path(ccx, start_def_id, start_fn_type)
1980                 };
1981
1982                 let args = {
1983                     let opaque_rust_main = "rust_main".with_c_str(|buf| {
1984                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1985                     });
1986
1987                     vec!(
1988                         opaque_rust_main,
1989                         llvm::LLVMGetParam(llfn, 0),
1990                         llvm::LLVMGetParam(llfn, 1)
1991                      )
1992                 };
1993                 (start_fn, args)
1994             } else {
1995                 debug!("using user-defined start fn");
1996                 let args = vec!(
1997                     llvm::LLVMGetParam(llfn, 0 as c_uint),
1998                     llvm::LLVMGetParam(llfn, 1 as c_uint)
1999                 );
2000
2001                 (rust_main, args)
2002             };
2003
2004             let result = llvm::LLVMBuildCall(bld,
2005                                              start_fn,
2006                                              args.as_ptr(),
2007                                              args.len() as c_uint,
2008                                              noname());
2009
2010             llvm::LLVMBuildRet(bld, result);
2011         }
2012     }
2013 }
2014
2015 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
2016                  ty: ty::t, attrs: &[ast::Attribute]) -> String {
2017     match attr::first_attr_value_str_by_name(attrs, "export_name") {
2018         // Use provided name
2019         Some(name) => name.get().to_string(),
2020
2021         _ => ccx.tcx.map.with_path(id, |mut path| {
2022             if attr::contains_name(attrs, "no_mangle") {
2023                 // Don't mangle
2024                 path.last().unwrap().to_string()
2025             } else {
2026                 match weak_lang_items::link_name(attrs) {
2027                     Some(name) => name.get().to_string(),
2028                     None => {
2029                         // Usual name mangling
2030                         mangle_exported_name(ccx, path, ty, id)
2031                     }
2032                 }
2033             }
2034         })
2035     }
2036 }
2037
2038 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
2039     debug!("get_item_val(id=`{:?}`)", id);
2040
2041     match ccx.item_vals.borrow().find_copy(&id) {
2042         Some(v) => return v,
2043         None => {}
2044     }
2045
2046     let mut foreign = false;
2047     let item = ccx.tcx.map.get(id);
2048     let val = match item {
2049         ast_map::NodeItem(i) => {
2050             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
2051             let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
2052
2053             let v = match i.node {
2054                 ast::ItemStatic(_, mutbl, ref expr) => {
2055                     // If this static came from an external crate, then
2056                     // we need to get the symbol from csearch instead of
2057                     // using the current crate's name/version
2058                     // information in the hash of the symbol
2059                     debug!("making {}", sym);
2060                     let (sym, is_local) = {
2061                         match ccx.external_srcs.borrow().find(&i.id) {
2062                             Some(&did) => {
2063                                 debug!("but found in other crate...");
2064                                 (csearch::get_symbol(&ccx.sess().cstore,
2065                                                      did), false)
2066                             }
2067                             None => (sym, true)
2068                         }
2069                     };
2070
2071                     // We need the translated value here, because for enums the
2072                     // LLVM type is not fully determined by the Rust type.
2073                     let (v, inlineable) = consts::const_expr(ccx, &**expr, is_local);
2074                     ccx.const_values.borrow_mut().insert(id, v);
2075                     let mut inlineable = inlineable;
2076
2077                     unsafe {
2078                         let llty = llvm::LLVMTypeOf(v);
2079                         let g = sym.as_slice().with_c_str(|buf| {
2080                             llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2081                         });
2082
2083                         if !ccx.reachable.contains(&id) {
2084                             llvm::SetLinkage(g, llvm::InternalLinkage);
2085                         }
2086
2087                         // Apply the `unnamed_addr` attribute if
2088                         // requested
2089                         if !ast_util::static_has_significant_address(
2090                                 mutbl,
2091                                 i.attrs.as_slice()) {
2092                             llvm::SetUnnamedAddr(g, true);
2093
2094                             // This is a curious case where we must make
2095                             // all of these statics inlineable. If a
2096                             // global is not tagged as `#[inline(never)]`,
2097                             // then LLVM won't coalesce globals unless they
2098                             // have an internal linkage type. This means that
2099                             // external crates cannot use this global.
2100                             // This is a problem for things like inner
2101                             // statics in generic functions, because the
2102                             // function will be inlined into another
2103                             // crate and then attempt to link to the
2104                             // static in the original crate, only to
2105                             // find that it's not there. On the other
2106                             // side of inlining, the crates knows to
2107                             // not declare this static as
2108                             // available_externally (because it isn't)
2109                             inlineable = true;
2110                         }
2111
2112                         if attr::contains_name(i.attrs.as_slice(),
2113                                                "thread_local") {
2114                             llvm::set_thread_local(g, true);
2115                         }
2116
2117                         if !inlineable {
2118                             debug!("{} not inlined", sym);
2119                             ccx.non_inlineable_statics.borrow_mut()
2120                                                       .insert(id);
2121                         }
2122
2123                         ccx.item_symbols.borrow_mut().insert(i.id, sym);
2124                         g
2125                     }
2126                 }
2127
2128                 ast::ItemFn(_, _, abi, _, _) => {
2129                     let llfn = if abi == Rust {
2130                         register_fn(ccx, i.span, sym, i.id, ty)
2131                     } else {
2132                         foreign::register_rust_fn_with_foreign_abi(ccx,
2133                                                                    i.span,
2134                                                                    sym,
2135                                                                    i.id)
2136                     };
2137                     set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2138                     llfn
2139                 }
2140
2141                 _ => fail!("get_item_val: weird result in table")
2142             };
2143
2144             match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
2145                                                      "link_section") {
2146                 Some(sect) => unsafe {
2147                     sect.get().with_c_str(|buf| {
2148                         llvm::LLVMSetSection(v, buf);
2149                     })
2150                 },
2151                 None => ()
2152             }
2153
2154             v
2155         }
2156
2157         ast_map::NodeTraitMethod(trait_method) => {
2158             debug!("get_item_val(): processing a NodeTraitMethod");
2159             match *trait_method {
2160                 ast::Required(_) => {
2161                     ccx.sess().bug("unexpected variant: required trait method in \
2162                                    get_item_val()");
2163                 }
2164                 ast::Provided(m) => {
2165                     register_method(ccx, id, &*m)
2166                 }
2167             }
2168         }
2169
2170         ast_map::NodeMethod(m) => {
2171             register_method(ccx, id, &*m)
2172         }
2173
2174         ast_map::NodeForeignItem(ni) => {
2175             foreign = true;
2176
2177             match ni.node {
2178                 ast::ForeignItemFn(..) => {
2179                     let abi = ccx.tcx.map.get_foreign_abi(id);
2180                     let ty = ty::node_id_to_type(ccx.tcx(), ni.id);
2181                     let name = foreign::link_name(&*ni);
2182                     foreign::register_foreign_item_fn(ccx, abi, ty,
2183                                                       name.get().as_slice(),
2184                                                       Some(ni.span))
2185                 }
2186                 ast::ForeignItemStatic(..) => {
2187                     foreign::register_static(ccx, &*ni)
2188                 }
2189             }
2190         }
2191
2192         ast_map::NodeVariant(ref v) => {
2193             let llfn;
2194             let args = match v.node.kind {
2195                 ast::TupleVariantKind(ref args) => args,
2196                 ast::StructVariantKind(_) => {
2197                     fail!("struct variant kind unexpected in get_item_val")
2198                 }
2199             };
2200             assert!(args.len() != 0u);
2201             let ty = ty::node_id_to_type(ccx.tcx(), id);
2202             let parent = ccx.tcx.map.get_parent(id);
2203             let enm = ccx.tcx.map.expect_item(parent);
2204             let sym = exported_name(ccx,
2205                                     id,
2206                                     ty,
2207                                     enm.attrs.as_slice());
2208
2209             llfn = match enm.node {
2210                 ast::ItemEnum(_, _) => {
2211                     register_fn(ccx, (*v).span, sym, id, ty)
2212                 }
2213                 _ => fail!("NodeVariant, shouldn't happen")
2214             };
2215             set_inline_hint(llfn);
2216             llfn
2217         }
2218
2219         ast_map::NodeStructCtor(struct_def) => {
2220             // Only register the constructor if this is a tuple-like struct.
2221             let ctor_id = match struct_def.ctor_id {
2222                 None => {
2223                     ccx.sess().bug("attempt to register a constructor of \
2224                                     a non-tuple-like struct")
2225                 }
2226                 Some(ctor_id) => ctor_id,
2227             };
2228             let parent = ccx.tcx.map.get_parent(id);
2229             let struct_item = ccx.tcx.map.expect_item(parent);
2230             let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2231             let sym = exported_name(ccx,
2232                                     id,
2233                                     ty,
2234                                     struct_item.attrs
2235                                                .as_slice());
2236             let llfn = register_fn(ccx, struct_item.span,
2237                                    sym, ctor_id, ty);
2238             set_inline_hint(llfn);
2239             llfn
2240         }
2241
2242         ref variant => {
2243             ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2244                                    variant).as_slice())
2245         }
2246     };
2247
2248     // foreign items (extern fns and extern statics) don't have internal
2249     // linkage b/c that doesn't quite make sense. Otherwise items can
2250     // have internal linkage if they're not reachable.
2251     if !foreign && !ccx.reachable.contains(&id) {
2252         llvm::SetLinkage(val, llvm::InternalLinkage);
2253     }
2254
2255     ccx.item_vals.borrow_mut().insert(id, val);
2256     val
2257 }
2258
2259 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2260                    m: &ast::Method) -> ValueRef {
2261     let mty = ty::node_id_to_type(ccx.tcx(), id);
2262
2263     let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2264
2265     let llfn = register_fn(ccx, m.span, sym, id, mty);
2266     set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2267     llfn
2268 }
2269
2270 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2271     unsafe {
2272         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2273     }
2274 }
2275
2276 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2277     -> encoder::EncodeParams<'r> {
2278         encoder::EncodeParams {
2279             diag: cx.sess().diagnostic(),
2280             tcx: cx.tcx(),
2281             reexports2: &cx.exp_map2,
2282             item_symbols: &cx.item_symbols,
2283             non_inlineable_statics: &cx.non_inlineable_statics,
2284             link_meta: &cx.link_meta,
2285             cstore: &cx.sess().cstore,
2286             encode_inlined_item: ie,
2287             reachable: &cx.reachable,
2288         }
2289 }
2290
2291 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2292     use flate;
2293
2294     let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2295         *ty != config::CrateTypeExecutable
2296     });
2297     if !any_library {
2298         return Vec::new()
2299     }
2300
2301     let encode_inlined_item: encoder::EncodeInlinedItem =
2302         |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2303
2304     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2305     let metadata = encoder::encode_metadata(encode_parms, krate);
2306     let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2307                      .append(match flate::deflate_bytes(metadata.as_slice()) {
2308                          Some(compressed) => compressed,
2309                          None => {
2310                              cx.sess().fatal("failed to compress metadata")
2311                          }
2312                      }.as_slice());
2313     let llmeta = C_bytes(cx, compressed.as_slice());
2314     let llconst = C_struct(cx, [llmeta], false);
2315     let name = format!("rust_metadata_{}_{}",
2316                        cx.link_meta.crate_name,
2317                        cx.link_meta.crate_hash);
2318     let llglobal = name.with_c_str(|buf| {
2319         unsafe {
2320             llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2321         }
2322     });
2323     unsafe {
2324         llvm::LLVMSetInitializer(llglobal, llconst);
2325         let name = loader::meta_section_name(cx.sess().targ_cfg.os);
2326         name.unwrap_or("rust_metadata").with_c_str(|buf| {
2327             llvm::LLVMSetSection(llglobal, buf)
2328         });
2329     }
2330     return metadata;
2331 }
2332
2333 pub fn trans_crate(krate: ast::Crate,
2334                    analysis: CrateAnalysis) -> (ty::ctxt, CrateTranslation) {
2335     let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, name, .. } = analysis;
2336
2337     // Before we touch LLVM, make sure that multithreading is enabled.
2338     unsafe {
2339         use std::sync::{Once, ONCE_INIT};
2340         static mut INIT: Once = ONCE_INIT;
2341         static mut POISONED: bool = false;
2342         INIT.doit(|| {
2343             if llvm::LLVMStartMultithreaded() != 1 {
2344                 // use an extra bool to make sure that all future usage of LLVM
2345                 // cannot proceed despite the Once not running more than once.
2346                 POISONED = true;
2347             }
2348         });
2349
2350         if POISONED {
2351             tcx.sess.bug("couldn't enable multi-threaded LLVM");
2352         }
2353     }
2354
2355     let link_meta = link::build_link_meta(&tcx.sess, &krate, name);
2356
2357     // Append ".rs" to crate name as LLVM module identifier.
2358     //
2359     // LLVM code generator emits a ".file filename" directive
2360     // for ELF backends. Value of the "filename" is set as the
2361     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2362     // crashes if the module identifier is same as other symbols
2363     // such as a function name in the module.
2364     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2365     let mut llmod_id = link_meta.crate_name.clone();
2366     llmod_id.push_str(".rs");
2367
2368     let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2369                                 Sha256::new(), link_meta, reachable);
2370
2371     // First, verify intrinsics.
2372     intrinsic::check_intrinsics(&ccx);
2373
2374     // Next, translate the module.
2375     {
2376         let _icx = push_ctxt("text");
2377         trans_mod(&ccx, &krate.module);
2378     }
2379
2380     glue::emit_tydescs(&ccx);
2381     if ccx.sess().opts.debuginfo != NoDebugInfo {
2382         debuginfo::finalize(&ccx);
2383     }
2384
2385     // Translate the metadata.
2386     let metadata = write_metadata(&ccx, &krate);
2387     if ccx.sess().trans_stats() {
2388         println!("--- trans stats ---");
2389         println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2390         println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2391         println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2392         println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2393
2394         println!("n_fns: {}", ccx.stats.n_fns.get());
2395         println!("n_monos: {}", ccx.stats.n_monos.get());
2396         println!("n_inlines: {}", ccx.stats.n_inlines.get());
2397         println!("n_closures: {}", ccx.stats.n_closures.get());
2398         println!("fn stats:");
2399         ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2400             insns_b.cmp(&insns_a)
2401         });
2402         for tuple in ccx.stats.fn_stats.borrow().iter() {
2403             match *tuple {
2404                 (ref name, ms, insns) => {
2405                     println!("{} insns, {} ms, {}", insns, ms, *name);
2406                 }
2407             }
2408         }
2409     }
2410     if ccx.sess().count_llvm_insns() {
2411         for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2412             println!("{:7u} {}", *v, *k);
2413         }
2414     }
2415
2416     let llcx = ccx.llcx;
2417     let link_meta = ccx.link_meta.clone();
2418     let llmod = ccx.llmod;
2419
2420     let mut reachable: Vec<String> = ccx.reachable.iter().filter_map(|id| {
2421         ccx.item_symbols.borrow().find(id).map(|s| s.to_string())
2422     }).collect();
2423
2424     // For the purposes of LTO, we add to the reachable set all of the upstream
2425     // reachable extern fns. These functions are all part of the public ABI of
2426     // the final product, so LTO needs to preserve them.
2427     ccx.sess().cstore.iter_crate_data(|cnum, _| {
2428         let syms = csearch::get_reachable_extern_fns(&ccx.sess().cstore, cnum);
2429         reachable.extend(syms.move_iter().map(|did| {
2430             csearch::get_symbol(&ccx.sess().cstore, did)
2431         }));
2432     });
2433
2434     // Make sure that some other crucial symbols are not eliminated from the
2435     // module. This includes the main function, the crate map (used for debug
2436     // log settings and I/O), and finally the curious rust_stack_exhausted
2437     // symbol. This symbol is required for use by the libmorestack library that
2438     // we link in, so we must ensure that this symbol is not internalized (if
2439     // defined in the crate).
2440     reachable.push("main".to_string());
2441     reachable.push("rust_stack_exhausted".to_string());
2442
2443     // referenced from .eh_frame section on some platforms
2444     reachable.push("rust_eh_personality".to_string());
2445     // referenced from rt/rust_try.ll
2446     reachable.push("rust_eh_personality_catch".to_string());
2447
2448     let metadata_module = ccx.metadata_llmod;
2449     let formats = ccx.tcx.dependency_formats.borrow().clone();
2450     let no_builtins = attr::contains_name(krate.attrs.as_slice(), "no_builtins");
2451
2452     (ccx.tcx, CrateTranslation {
2453         context: llcx,
2454         module: llmod,
2455         link: link_meta,
2456         metadata_module: metadata_module,
2457         metadata: metadata,
2458         reachable: reachable,
2459         crate_formats: formats,
2460         no_builtins: no_builtins,
2461     })
2462 }