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