]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
auto merge of #9244 : thestinger/rust/drop, r=catamorphism
[rust.git] / src / librustc / middle / trans / base.rs
1 // Copyright 2012-2013 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 many TypeRefs correspond to one ty::t; for instance, tup(int, int,
24 //     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26
27 use back::link::{mangle_exported_name};
28 use back::{link, abi};
29 use driver::session;
30 use driver::session::Session;
31 use driver::driver::{CrateAnalysis, CrateTranslation};
32 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
33 use lib::llvm::{llvm, True};
34 use lib;
35 use metadata::common::LinkMeta;
36 use metadata::{csearch, cstore, encoder};
37 use middle::astencode;
38 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
39 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::base;
43 use middle::trans::build::*;
44 use middle::trans::builder::{Builder, noname};
45 use middle::trans::callee;
46 use middle::trans::common::*;
47 use middle::trans::consts;
48 use middle::trans::controlflow;
49 use middle::trans::datum;
50 use middle::trans::debuginfo;
51 use middle::trans::expr;
52 use middle::trans::foreign;
53 use middle::trans::glue;
54 use middle::trans::inline;
55 use middle::trans::llrepr::LlvmRepr;
56 use middle::trans::machine;
57 use middle::trans::machine::{llalign_of_min, llsize_of};
58 use middle::trans::meth;
59 use middle::trans::monomorphize;
60 use middle::trans::tvec;
61 use middle::trans::type_of;
62 use middle::trans::type_of::*;
63 use middle::trans::value::Value;
64 use middle::ty;
65 use util::common::indenter;
66 use util::ppaux::{Repr, ty_to_str};
67
68 use middle::trans::type_::Type;
69
70 use std::c_str::ToCStr;
71 use std::hash;
72 use std::hashmap::HashMap;
73 use std::io;
74 use std::libc::c_uint;
75 use std::vec;
76 use std::local_data;
77 use extra::time;
78 use extra::sort;
79 use syntax::ast::Name;
80 use syntax::ast_map::{path, path_elt_to_str, path_name, path_pretty_name};
81 use syntax::ast_util::{local_def};
82 use syntax::attr;
83 use syntax::attr::AttrMetaMethods;
84 use syntax::codemap::Span;
85 use syntax::parse::token;
86 use syntax::parse::token::{special_idents};
87 use syntax::print::pprust::stmt_to_str;
88 use syntax::{ast, ast_util, codemap, ast_map};
89 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
90 use syntax::visit;
91 use syntax::visit::Visitor;
92
93 pub use middle::trans::context::task_llcx;
94
95 static task_local_insn_key: local_data::Key<@~[&'static str]> = &local_data::Key;
96
97 pub fn with_insn_ctxt(blk: &fn(&[&'static str])) {
98     let opt = local_data::get(task_local_insn_key, |k| k.map_move(|k| *k));
99     if opt.is_some() {
100         blk(*opt.unwrap());
101     }
102 }
103
104 pub fn init_insn_ctxt() {
105     local_data::set(task_local_insn_key, @~[]);
106 }
107
108 pub struct _InsnCtxt { _x: () }
109
110 #[unsafe_destructor]
111 impl Drop for _InsnCtxt {
112     fn drop(&mut self) {
113         do local_data::modify(task_local_insn_key) |c| {
114             do c.map_move |ctx| {
115                 let mut ctx = (*ctx).clone();
116                 ctx.pop();
117                 @ctx
118             }
119         }
120     }
121 }
122
123 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
124     debug!("new InsnCtxt: %s", s);
125     do local_data::modify(task_local_insn_key) |c| {
126         do c.map_move |ctx| {
127             let mut ctx = (*ctx).clone();
128             ctx.push(s);
129             @ctx
130         }
131     }
132     _InsnCtxt { _x: () }
133 }
134
135 struct StatRecorder<'self> {
136     ccx: @mut CrateContext,
137     name: &'self str,
138     start: u64,
139     istart: uint,
140 }
141
142 impl<'self> StatRecorder<'self> {
143     pub fn new(ccx: @mut CrateContext,
144                name: &'self str) -> StatRecorder<'self> {
145         let start = if ccx.sess.trans_stats() {
146             time::precise_time_ns()
147         } else {
148             0
149         };
150         let istart = ccx.stats.n_llvm_insns;
151         StatRecorder {
152             ccx: ccx,
153             name: name,
154             start: start,
155             istart: istart,
156         }
157     }
158 }
159
160 #[unsafe_destructor]
161 impl<'self> Drop for StatRecorder<'self> {
162     fn drop(&mut self) {
163         if self.ccx.sess.trans_stats() {
164             let end = time::precise_time_ns();
165             let elapsed = ((end - self.start) / 1_000_000) as uint;
166             let iend = self.ccx.stats.n_llvm_insns;
167             self.ccx.stats.fn_stats.push((self.name.to_owned(),
168                                           elapsed,
169                                           iend - self.istart));
170             self.ccx.stats.n_fns += 1;
171             // Reset LLVM insn count to avoid compound costs.
172             self.ccx.stats.n_llvm_insns = self.istart;
173         }
174     }
175 }
176
177 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
178 pub fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
179     let llfn: ValueRef = do name.with_c_str |buf| {
180         unsafe {
181             llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
182         }
183     };
184
185     lib::llvm::SetFunctionCallConv(llfn, cc);
186     return llfn;
187 }
188
189 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
190 pub fn decl_cdecl_fn(llmod: ModuleRef, name: &str, ty: Type) -> ValueRef {
191     return decl_fn(llmod, name, lib::llvm::CCallConv, ty);
192 }
193
194 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
195 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef, name: &str,
196                      cc: lib::llvm::CallConv, ty: Type) -> ValueRef {
197     match externs.find_equiv(&name) {
198         Some(n) => return *n,
199         None => ()
200     }
201     let f = decl_fn(llmod, name, cc, ty);
202     externs.insert(name.to_owned(), f);
203     f
204 }
205
206 pub fn get_extern_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t,
207                           name: &str) -> ValueRef {
208     match ccx.externs.find_equiv(&name) {
209         Some(n) => return *n,
210         None => ()
211     }
212     let f = decl_rust_fn(ccx, inputs, output, name);
213     ccx.externs.insert(name.to_owned(), f);
214     f
215 }
216
217 pub fn decl_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t,
218                     name: &str) -> ValueRef {
219     let llfty = type_of_rust_fn(ccx, inputs, output);
220     let llfn = decl_cdecl_fn(ccx.llmod, name, llfty);
221
222     match ty::get(output).sty {
223         // `~` pointer return values never alias because ownership is transferred
224         ty::ty_uniq(*) |
225         ty::ty_evec(_, ty::vstore_uniq) => {
226             unsafe {
227                 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
228             }
229         }
230         _ => ()
231     }
232
233     let uses_outptr = type_of::return_uses_outptr(ccx.tcx, output);
234     let offset = if uses_outptr { 2 } else { 1 };
235
236     for (i, &arg_ty) in inputs.iter().enumerate() {
237         let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
238         match ty::get(arg_ty).sty {
239             // `~` pointer parameters never alias because ownership is transferred
240             ty::ty_uniq(*) |
241             ty::ty_evec(_, ty::vstore_uniq) |
242             ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, _}) => {
243                 unsafe {
244                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
245                 }
246             }
247             _ => ()
248         }
249     }
250
251     // The out pointer will never alias with any other pointers, as the object only exists at a
252     // language level after the call. It can also be tagged with SRet to indicate that it is
253     // guaranteed to point to a usable block of memory for the type.
254     if uses_outptr {
255         unsafe {
256             let outptr = llvm::LLVMGetParam(llfn, 0);
257             llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
258             llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
259         }
260     }
261
262     llfn
263 }
264
265 pub fn decl_internal_rust_fn(ccx: &mut CrateContext, inputs: &[ty::t], output: ty::t,
266                              name: &str) -> ValueRef {
267     let llfn = decl_rust_fn(ccx, inputs, output, name);
268     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
269     llfn
270 }
271
272 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
273                         name: &str, ty: Type) -> ValueRef {
274     match externs.find_equiv(&name) {
275         Some(n) => return *n,
276         None => ()
277     }
278     unsafe {
279         let c = do name.with_c_str |buf| {
280             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
281         };
282         externs.insert(name.to_owned(), c);
283         return c;
284     }
285 }
286 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
287     let _icx = push_ctxt("umax");
288     let cond = ICmp(cx, lib::llvm::IntULT, a, b);
289     return Select(cx, cond, b, a);
290 }
291
292 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
293     let _icx = push_ctxt("umin");
294     let cond = ICmp(cx, lib::llvm::IntULT, a, b);
295     return Select(cx, cond, a, b);
296 }
297
298 // Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
299 // The type of the returned pointer is always i8*.  If you care about the
300 // return type, use bump_ptr().
301 pub fn ptr_offs(bcx: @mut Block, base: ValueRef, sz: ValueRef) -> ValueRef {
302     let _icx = push_ctxt("ptr_offs");
303     let raw = PointerCast(bcx, base, Type::i8p());
304     InBoundsGEP(bcx, raw, [sz])
305 }
306
307 // Increment a pointer by a given amount and then cast it to be a pointer
308 // to a given type.
309 pub fn bump_ptr(bcx: @mut Block, t: ty::t, base: ValueRef, sz: ValueRef) ->
310    ValueRef {
311     let _icx = push_ctxt("bump_ptr");
312     let ccx = bcx.ccx();
313     let bumped = ptr_offs(bcx, base, sz);
314     let typ = type_of(ccx, t).ptr_to();
315     PointerCast(bcx, bumped, typ)
316 }
317
318 // Returns a pointer to the body for the box. The box may be an opaque
319 // box. The result will be casted to the type of body_t, if it is statically
320 // known.
321 //
322 // The runtime equivalent is box_body() in "rust_internal.h".
323 pub fn opaque_box_body(bcx: @mut Block,
324                        body_t: ty::t,
325                        boxptr: ValueRef) -> ValueRef {
326     let _icx = push_ctxt("opaque_box_body");
327     let ccx = bcx.ccx();
328     let ty = type_of(ccx, body_t);
329     let ty = Type::box(ccx, &ty);
330     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
331     GEPi(bcx, boxptr, [0u, abi::box_field_body])
332 }
333
334 // malloc_raw_dyn: allocates a box to contain a given type, but with a
335 // potentially dynamic size.
336 pub fn malloc_raw_dyn(bcx: @mut Block,
337                       t: ty::t,
338                       heap: heap,
339                       size: ValueRef) -> Result {
340     let _icx = push_ctxt("malloc_raw");
341     let ccx = bcx.ccx();
342
343     fn require_alloc_fn(bcx: @mut Block, t: ty::t, it: LangItem) -> ast::DefId {
344         let li = &bcx.tcx().lang_items;
345         match li.require(it) {
346             Ok(id) => id,
347             Err(s) => {
348                 bcx.tcx().sess.fatal(fmt!("allocation of `%s` %s",
349                                           bcx.ty_to_str(t), s));
350             }
351         }
352     }
353
354     if heap == heap_exchange {
355         let llty_value = type_of::type_of(ccx, t);
356
357
358         // Allocate space:
359         let r = callee::trans_lang_call(
360             bcx,
361             require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
362             [size],
363             None);
364         rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
365     } else {
366         // we treat ~fn, @fn and @[] as @ here, which isn't ideal
367         let (mk_fn, langcall) = match heap {
368             heap_managed | heap_managed_unique => {
369                 (ty::mk_imm_box,
370                  require_alloc_fn(bcx, t, MallocFnLangItem))
371             }
372             heap_exchange_closure => {
373                 (ty::mk_imm_box,
374                  require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem))
375             }
376             _ => fail!("heap_exchange already handled")
377         };
378
379         // Grab the TypeRef type of box_ptr_ty.
380         let box_ptr_ty = mk_fn(bcx.tcx(), t);
381         let llty = type_of(ccx, box_ptr_ty);
382
383         // Get the tydesc for the body:
384         let static_ti = get_tydesc(ccx, t);
385         glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
386
387         // Allocate space:
388         let tydesc = PointerCast(bcx, static_ti.tydesc, Type::i8p());
389         let r = callee::trans_lang_call(
390             bcx,
391             langcall,
392             [tydesc, size],
393             None);
394         let r = rslt(r.bcx, PointerCast(r.bcx, r.val, llty));
395         maybe_set_managed_unique_rc(r.bcx, r.val, heap);
396         r
397     }
398 }
399
400 // malloc_raw: expects an unboxed type and returns a pointer to
401 // enough space for a box of that type.  This includes a rust_opaque_box
402 // header.
403 pub fn malloc_raw(bcx: @mut Block, t: ty::t, heap: heap) -> Result {
404     let ty = type_of(bcx.ccx(), t);
405     let size = llsize_of(bcx.ccx(), ty);
406     malloc_raw_dyn(bcx, t, heap, size)
407 }
408
409 pub struct MallocResult {
410     bcx: @mut Block,
411     box: ValueRef,
412     body: ValueRef
413 }
414
415 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
416 // and pulls out the body
417 pub fn malloc_general_dyn(bcx: @mut Block, t: ty::t, heap: heap, size: ValueRef)
418     -> MallocResult {
419     assert!(heap != heap_exchange);
420     let _icx = push_ctxt("malloc_general");
421     let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
422     let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
423
424     MallocResult { bcx: bcx, box: llbox, body: body }
425 }
426
427 pub fn malloc_general(bcx: @mut Block, t: ty::t, heap: heap) -> MallocResult {
428     let ty = type_of(bcx.ccx(), t);
429     assert!(heap != heap_exchange);
430     malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
431 }
432 pub fn malloc_boxed(bcx: @mut Block, t: ty::t)
433     -> MallocResult {
434     malloc_general(bcx, t, heap_managed)
435 }
436
437 pub fn heap_for_unique(bcx: @mut Block, t: ty::t) -> heap {
438     if ty::type_contents(bcx.tcx(), t).contains_managed() {
439         heap_managed_unique
440     } else {
441         heap_exchange
442     }
443 }
444
445 pub fn maybe_set_managed_unique_rc(bcx: @mut Block, bx: ValueRef, heap: heap) {
446     assert!(heap != heap_exchange);
447     if heap == heap_managed_unique {
448         // In cases where we are looking at a unique-typed allocation in the
449         // managed heap (thus have refcount 1 from the managed allocator),
450         // such as a ~(@foo) or such. These need to have their refcount forced
451         // to -2 so the annihilator ignores them.
452         let rc = GEPi(bcx, bx, [0u, abi::box_field_refcnt]);
453         let rc_val = C_int(bcx.ccx(), -2);
454         Store(bcx, rc_val, rc);
455     }
456 }
457
458 // Type descriptor and type glue stuff
459
460 pub fn get_tydesc_simple(ccx: &mut CrateContext, t: ty::t) -> ValueRef {
461     get_tydesc(ccx, t).tydesc
462 }
463
464 pub fn get_tydesc(ccx: &mut CrateContext, t: ty::t) -> @mut tydesc_info {
465     match ccx.tydescs.find(&t) {
466         Some(&inf) => {
467             return inf;
468         }
469         _ => { }
470     }
471
472     ccx.stats.n_static_tydescs += 1u;
473     let inf = glue::declare_tydesc(ccx, t);
474     ccx.tydescs.insert(t, inf);
475     return inf;
476 }
477
478 pub fn set_optimize_for_size(f: ValueRef) {
479     lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
480 }
481
482 pub fn set_no_inline(f: ValueRef) {
483     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
484 }
485
486 pub fn set_no_unwind(f: ValueRef) {
487     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
488 }
489
490 // Tell LLVM to emit the information necessary to unwind the stack for the
491 // function f.
492 pub fn set_uwtable(f: ValueRef) {
493     lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
494 }
495
496 pub fn set_inline_hint(f: ValueRef) {
497     lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
498 }
499
500 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
501     use syntax::attr::*;
502     // Set the inline hint if there is one
503     match find_inline_attr(attrs) {
504         InlineHint   => set_inline_hint(llfn),
505         InlineAlways => set_always_inline(llfn),
506         InlineNever  => set_no_inline(llfn),
507         InlineNone   => { /* fallthrough */ }
508     }
509
510     // Add the no-split-stack attribute if requested
511     if contains_name(attrs, "no_split_stack") {
512         set_no_split_stack(llfn);
513     }
514 }
515
516 pub fn set_always_inline(f: ValueRef) {
517     lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
518 }
519
520 pub fn set_fixed_stack_segment(f: ValueRef) {
521     do "fixed-stack-segment".to_c_str().with_ref |buf| {
522         unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
523     }
524 }
525
526 pub fn set_no_split_stack(f: ValueRef) {
527     do "no-split-stack".to_c_str().with_ref |buf| {
528         unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
529     }
530 }
531
532 pub fn set_glue_inlining(f: ValueRef, t: ty::t) {
533     if ty::type_is_structural(t) {
534         set_optimize_for_size(f);
535     } else { set_always_inline(f); }
536 }
537
538 // Double-check that we never ask LLVM to declare the same symbol twice. It
539 // silently mangles such symbols, breaking our linkage model.
540 pub fn note_unique_llvm_symbol(ccx: &mut CrateContext, sym: @str) {
541     if ccx.all_llvm_symbols.contains(&sym) {
542         ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
543     }
544     ccx.all_llvm_symbols.insert(sym);
545 }
546
547
548 pub fn get_res_dtor(ccx: @mut CrateContext,
549                     did: ast::DefId,
550                     parent_id: ast::DefId,
551                     substs: &[ty::t])
552                  -> ValueRef {
553     let _icx = push_ctxt("trans_res_dtor");
554     if !substs.is_empty() {
555         let did = if did.crate != ast::LOCAL_CRATE {
556             inline::maybe_instantiate_inline(ccx, did)
557         } else {
558             did
559         };
560         assert_eq!(did.crate, ast::LOCAL_CRATE);
561         let tsubsts = ty::substs {regions: ty::ErasedRegions,
562                                   self_ty: None,
563                                   tps: /*bad*/ substs.to_owned() };
564         let (val, _) = monomorphize::monomorphic_fn(ccx,
565                                                     did,
566                                                     &tsubsts,
567                                                     None,
568                                                     None,
569                                                     None);
570
571         val
572     } else if did.crate == ast::LOCAL_CRATE {
573         get_item_val(ccx, did.node)
574     } else {
575         let tcx = ccx.tcx;
576         let name = csearch::get_symbol(ccx.sess.cstore, did);
577         let class_ty = ty::subst_tps(tcx,
578                                      substs,
579                                      None,
580                                      ty::lookup_item_type(tcx, parent_id).ty);
581         let llty = type_of_dtor(ccx, class_ty);
582         get_extern_fn(&mut ccx.externs,
583                       ccx.llmod,
584                       name,
585                       lib::llvm::CCallConv,
586                       llty)
587     }
588 }
589
590 // Structural comparison: a rather involved form of glue.
591 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
592     if cx.sess.opts.save_temps {
593         do s.with_c_str |buf| {
594             unsafe {
595                 llvm::LLVMSetValueName(v, buf)
596             }
597         }
598     }
599 }
600
601
602 // Used only for creating scalar comparison glue.
603 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
604
605 // NB: This produces an i1, not a Rust bool (i8).
606 pub fn compare_scalar_types(cx: @mut Block,
607                             lhs: ValueRef,
608                             rhs: ValueRef,
609                             t: ty::t,
610                             op: ast::BinOp)
611                          -> Result {
612     let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
613
614     match ty::get(t).sty {
615         ty::ty_nil => rslt(cx, f(nil_type)),
616         ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
617         ty::ty_char => rslt(cx, f(unsigned_int)),
618         ty::ty_int(_) => rslt(cx, f(signed_int)),
619         ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
620         ty::ty_float(_) => rslt(cx, f(floating_point)),
621         ty::ty_type => {
622             rslt(
623                 controlflow::trans_fail(
624                     cx, None,
625                     @"attempt to compare values of type type"),
626                 C_nil())
627         }
628         _ => {
629             // Should never get here, because t is scalar.
630             cx.sess().bug("non-scalar type passed to \
631                            compare_scalar_types")
632         }
633     }
634 }
635
636
637 // A helper function to do the actual comparison of scalar values.
638 pub fn compare_scalar_values(cx: @mut Block,
639                              lhs: ValueRef,
640                              rhs: ValueRef,
641                              nt: scalar_type,
642                              op: ast::BinOp)
643                           -> ValueRef {
644     let _icx = push_ctxt("compare_scalar_values");
645     fn die(cx: @mut Block) -> ! {
646         cx.tcx().sess.bug("compare_scalar_values: must be a\
647                            comparison operator");
648     }
649     match nt {
650       nil_type => {
651         // We don't need to do actual comparisons for nil.
652         // () == () holds but () < () does not.
653         match op {
654           ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(true),
655           ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(false),
656           // refinements would be nice
657           _ => die(cx)
658         }
659       }
660       floating_point => {
661         let cmp = match op {
662           ast::BiEq => lib::llvm::RealOEQ,
663           ast::BiNe => lib::llvm::RealUNE,
664           ast::BiLt => lib::llvm::RealOLT,
665           ast::BiLe => lib::llvm::RealOLE,
666           ast::BiGt => lib::llvm::RealOGT,
667           ast::BiGe => lib::llvm::RealOGE,
668           _ => die(cx)
669         };
670         return FCmp(cx, cmp, lhs, rhs);
671       }
672       signed_int => {
673         let cmp = match op {
674           ast::BiEq => lib::llvm::IntEQ,
675           ast::BiNe => lib::llvm::IntNE,
676           ast::BiLt => lib::llvm::IntSLT,
677           ast::BiLe => lib::llvm::IntSLE,
678           ast::BiGt => lib::llvm::IntSGT,
679           ast::BiGe => lib::llvm::IntSGE,
680           _ => die(cx)
681         };
682         return ICmp(cx, cmp, lhs, rhs);
683       }
684       unsigned_int => {
685         let cmp = match op {
686           ast::BiEq => lib::llvm::IntEQ,
687           ast::BiNe => lib::llvm::IntNE,
688           ast::BiLt => lib::llvm::IntULT,
689           ast::BiLe => lib::llvm::IntULE,
690           ast::BiGt => lib::llvm::IntUGT,
691           ast::BiGe => lib::llvm::IntUGE,
692           _ => die(cx)
693         };
694         return ICmp(cx, cmp, lhs, rhs);
695       }
696     }
697 }
698
699 pub type val_and_ty_fn<'self> = &'self fn(@mut Block, ValueRef, ty::t) -> @mut Block;
700
701 pub fn load_inbounds(cx: @mut Block, p: ValueRef, idxs: &[uint]) -> ValueRef {
702     return Load(cx, GEPi(cx, p, idxs));
703 }
704
705 pub fn store_inbounds(cx: @mut Block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
706     Store(cx, v, GEPi(cx, p, idxs));
707 }
708
709 // Iterates through the elements of a structural type.
710 pub fn iter_structural_ty(cx: @mut Block, av: ValueRef, t: ty::t,
711                           f: val_and_ty_fn) -> @mut Block {
712     let _icx = push_ctxt("iter_structural_ty");
713
714     fn iter_variant(cx: @mut Block, repr: &adt::Repr, av: ValueRef,
715                     variant: @ty::VariantInfo,
716                     tps: &[ty::t], f: val_and_ty_fn) -> @mut Block {
717         let _icx = push_ctxt("iter_variant");
718         let tcx = cx.tcx();
719         let mut cx = cx;
720
721         for (i, &arg) in variant.args.iter().enumerate() {
722             cx = f(cx,
723                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
724                    ty::subst_tps(tcx, tps, None, arg));
725         }
726         return cx;
727     }
728
729     let mut cx = cx;
730     match ty::get(t).sty {
731       ty::ty_struct(*) => {
732           let repr = adt::represent_type(cx.ccx(), t);
733           do expr::with_field_tys(cx.tcx(), t, None) |discr, field_tys| {
734               for (i, field_ty) in field_tys.iter().enumerate() {
735                   let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
736                   cx = f(cx, llfld_a, field_ty.mt.ty);
737               }
738           }
739       }
740       ty::ty_estr(ty::vstore_fixed(_)) |
741       ty::ty_evec(_, ty::vstore_fixed(_)) => {
742         let (base, len) = tvec::get_base_and_len(cx, av, t);
743         cx = tvec::iter_vec_raw(cx, base, t, len, f);
744       }
745       ty::ty_tup(ref args) => {
746           let repr = adt::represent_type(cx.ccx(), t);
747           for (i, arg) in args.iter().enumerate() {
748               let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
749               cx = f(cx, llfld_a, *arg);
750           }
751       }
752       ty::ty_enum(tid, ref substs) => {
753           let ccx = cx.ccx();
754
755           let repr = adt::represent_type(ccx, t);
756           let variants = ty::enum_variants(ccx.tcx, tid);
757           let n_variants = (*variants).len();
758
759           // NB: we must hit the discriminant first so that structural
760           // comparison know not to proceed when the discriminants differ.
761
762           match adt::trans_switch(cx, repr, av) {
763               (_match::single, None) => {
764                   cx = iter_variant(cx, repr, av, variants[0],
765                                     substs.tps, f);
766               }
767               (_match::switch, Some(lldiscrim_a)) => {
768                   cx = f(cx, lldiscrim_a, ty::mk_int());
769                   let unr_cx = sub_block(cx, "enum-iter-unr");
770                   Unreachable(unr_cx);
771                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
772                                         n_variants);
773                   let next_cx = sub_block(cx, "enum-iter-next");
774
775                   for variant in (*variants).iter() {
776                       let variant_cx =
777                           sub_block(cx, ~"enum-iter-variant-" +
778                                     variant.disr_val.to_str());
779                       let variant_cx =
780                           iter_variant(variant_cx, repr, av, *variant,
781                                        substs.tps, |x,y,z| f(x,y,z));
782                       match adt::trans_case(cx, repr, variant.disr_val) {
783                           _match::single_result(r) => {
784                               AddCase(llswitch, r.val, variant_cx.llbb)
785                           }
786                           _ => ccx.sess.unimpl("value from adt::trans_case \
787                                                 in iter_structural_ty")
788                       }
789                       Br(variant_cx, next_cx.llbb);
790                   }
791                   cx = next_cx;
792               }
793               _ => ccx.sess.unimpl("value from adt::trans_switch \
794                                     in iter_structural_ty")
795           }
796       }
797       _ => cx.sess().unimpl("type in iter_structural_ty")
798     }
799     return cx;
800 }
801
802 pub fn cast_shift_expr_rhs(cx: @mut Block, op: ast::BinOp,
803                            lhs: ValueRef, rhs: ValueRef) -> ValueRef {
804     cast_shift_rhs(op, lhs, rhs,
805                    |a,b| Trunc(cx, a, b),
806                    |a,b| ZExt(cx, a, b))
807 }
808
809 pub fn cast_shift_const_rhs(op: ast::BinOp,
810                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
811     cast_shift_rhs(op, lhs, rhs,
812                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
813                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
814 }
815
816 pub fn cast_shift_rhs(op: ast::BinOp,
817                       lhs: ValueRef, rhs: ValueRef,
818                       trunc: &fn(ValueRef, Type) -> ValueRef,
819                       zext: &fn(ValueRef, Type) -> ValueRef)
820                    -> ValueRef {
821     // Shifts may have any size int on the rhs
822     unsafe {
823         if ast_util::is_shift_binop(op) {
824             let rhs_llty = val_ty(rhs);
825             let lhs_llty = val_ty(lhs);
826             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
827             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
828             if lhs_sz < rhs_sz {
829                 trunc(rhs, lhs_llty)
830             } else if lhs_sz > rhs_sz {
831                 // FIXME (#1877: If shifting by negative
832                 // values becomes not undefined then this is wrong.
833                 zext(rhs, lhs_llty)
834             } else {
835                 rhs
836             }
837         } else {
838             rhs
839         }
840     }
841 }
842
843 pub fn fail_if_zero(cx: @mut Block, span: Span, divrem: ast::BinOp,
844                     rhs: ValueRef, rhs_t: ty::t) -> @mut Block {
845     let text = if divrem == ast::BiDiv {
846         @"attempted to divide by zero"
847     } else {
848         @"attempted remainder with a divisor of zero"
849     };
850     let is_zero = match ty::get(rhs_t).sty {
851       ty::ty_int(t) => {
852         let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
853         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
854       }
855       ty::ty_uint(t) => {
856         let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
857         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
858       }
859       _ => {
860         cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
861                           ty_to_str(cx.ccx().tcx, rhs_t));
862       }
863     };
864     do with_cond(cx, is_zero) |bcx| {
865         controlflow::trans_fail(bcx, Some(span), text)
866     }
867 }
868
869 pub fn null_env_ptr(ccx: &CrateContext) -> ValueRef {
870     C_null(Type::opaque_box(ccx).ptr_to())
871 }
872
873 pub fn trans_external_path(ccx: &mut CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
874     let name = csearch::get_symbol(ccx.sess.cstore, did);
875     match ty::get(t).sty {
876         ty::ty_bare_fn(ref fn_ty) => {
877             match fn_ty.abis.for_arch(ccx.sess.targ_cfg.arch) {
878                 Some(Rust) | Some(RustIntrinsic) => {
879                     get_extern_rust_fn(ccx, fn_ty.sig.inputs, fn_ty.sig.output, name)
880                 }
881                 Some(*) | None => {
882                     let c = foreign::llvm_calling_convention(ccx, fn_ty.abis);
883                     let cconv = c.unwrap_or(lib::llvm::CCallConv);
884                     let llty = type_of_fn_from_ty(ccx, t);
885                     get_extern_fn(&mut ccx.externs, ccx.llmod, name, cconv, llty)
886                 }
887             }
888         }
889         ty::ty_closure(ref f) => {
890             get_extern_rust_fn(ccx, f.sig.inputs, f.sig.output, name)
891         }
892         _ => {
893             let llty = type_of(ccx, t);
894             get_extern_const(&mut ccx.externs, ccx.llmod, name, llty)
895         }
896     }
897 }
898
899 pub fn invoke(bcx: @mut Block, llfn: ValueRef, llargs: ~[ValueRef],
900               attributes: &[(uint, lib::llvm::Attribute)])
901            -> (ValueRef, @mut Block) {
902     let _icx = push_ctxt("invoke_");
903     if bcx.unreachable {
904         return (C_null(Type::i8()), bcx);
905     }
906
907     match bcx.node_info {
908         None => debug!("invoke at ???"),
909         Some(node_info) => {
910             debug!("invoke at %s",
911                    bcx.sess().codemap.span_to_str(node_info.span));
912         }
913     }
914
915     if need_invoke(bcx) {
916         unsafe {
917             debug!("invoking %x at %x",
918                    ::std::cast::transmute(llfn),
919                    ::std::cast::transmute(bcx.llbb));
920             for &llarg in llargs.iter() {
921                 debug!("arg: %x", ::std::cast::transmute(llarg));
922             }
923         }
924         let normal_bcx = sub_block(bcx, "normal return");
925         let llresult = Invoke(bcx,
926                               llfn,
927                               llargs,
928                               normal_bcx.llbb,
929                               get_landing_pad(bcx),
930                               attributes);
931         return (llresult, normal_bcx);
932     } else {
933         unsafe {
934             debug!("calling %x at %x",
935                    ::std::cast::transmute(llfn),
936                    ::std::cast::transmute(bcx.llbb));
937             for &llarg in llargs.iter() {
938                 debug!("arg: %x", ::std::cast::transmute(llarg));
939             }
940         }
941         let llresult = Call(bcx, llfn, llargs, attributes);
942         return (llresult, bcx);
943     }
944 }
945
946 pub fn need_invoke(bcx: @mut Block) -> bool {
947     if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
948         return false;
949     }
950
951     // Avoid using invoke if we are already inside a landing pad.
952     if bcx.is_lpad {
953         return false;
954     }
955
956     if have_cached_lpad(bcx) {
957         return true;
958     }
959
960     // Walk the scopes to look for cleanups
961     let mut cur = bcx;
962     let mut cur_scope = cur.scope;
963     loop {
964         cur_scope = match cur_scope {
965             Some(inf) => {
966                 for cleanup in inf.cleanups.iter() {
967                     match *cleanup {
968                         clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
969                             if cleanup_type == normal_exit_and_unwind {
970                                 return true;
971                             }
972                         }
973                     }
974                 }
975                 inf.parent
976             }
977             None => {
978                 cur = match cur.parent {
979                     Some(next) => next,
980                     None => return false
981                 };
982                 cur.scope
983             }
984         }
985     }
986 }
987
988 pub fn have_cached_lpad(bcx: @mut Block) -> bool {
989     let mut res = false;
990     do in_lpad_scope_cx(bcx) |inf| {
991         match inf.landing_pad {
992           Some(_) => res = true,
993           None => res = false
994         }
995     }
996     return res;
997 }
998
999 pub fn in_lpad_scope_cx(bcx: @mut Block, f: &fn(si: &mut ScopeInfo)) {
1000     let mut bcx = bcx;
1001     let mut cur_scope = bcx.scope;
1002     loop {
1003         cur_scope = match cur_scope {
1004             Some(inf) => {
1005                 if !inf.empty_cleanups() || (inf.parent.is_none() && bcx.parent.is_none()) {
1006                     f(inf);
1007                     return;
1008                 }
1009                 inf.parent
1010             }
1011             None => {
1012                 bcx = block_parent(bcx);
1013                 bcx.scope
1014             }
1015         }
1016     }
1017 }
1018
1019 pub fn get_landing_pad(bcx: @mut Block) -> BasicBlockRef {
1020     let _icx = push_ctxt("get_landing_pad");
1021
1022     let mut cached = None;
1023     let mut pad_bcx = bcx; // Guaranteed to be set below
1024     do in_lpad_scope_cx(bcx) |inf| {
1025         // If there is a valid landing pad still around, use it
1026         match inf.landing_pad {
1027           Some(target) => cached = Some(target),
1028           None => {
1029             pad_bcx = lpad_block(bcx, "unwind");
1030             inf.landing_pad = Some(pad_bcx.llbb);
1031           }
1032         }
1033     }
1034     // Can't return from block above
1035     match cached { Some(b) => return b, None => () }
1036     // The landing pad return type (the type being propagated). Not sure what
1037     // this represents but it's determined by the personality function and
1038     // this is what the EH proposal example uses.
1039     let llretty = Type::struct_([Type::i8p(), Type::i32()], false);
1040     // The exception handling personality function. This is the C++
1041     // personality function __gxx_personality_v0, wrapped in our naming
1042     // convention.
1043     let personality = bcx.ccx().upcalls.rust_personality;
1044     // The only landing pad clause will be 'cleanup'
1045     let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
1046     // The landing pad block is a cleanup
1047     SetCleanup(pad_bcx, llretval);
1048
1049     // Because we may have unwound across a stack boundary, we must call into
1050     // the runtime to figure out which stack segment we are on and place the
1051     // stack limit back into the TLS.
1052     Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, [], []);
1053
1054     // We store the retval in a function-central alloca, so that calls to
1055     // Resume can find it.
1056     match bcx.fcx.personality {
1057       Some(addr) => Store(pad_bcx, llretval, addr),
1058       None => {
1059         let addr = alloca(pad_bcx, val_ty(llretval), "");
1060         bcx.fcx.personality = Some(addr);
1061         Store(pad_bcx, llretval, addr);
1062       }
1063     }
1064
1065     // Unwind all parent scopes, and finish with a Resume instr
1066     cleanup_and_leave(pad_bcx, None, None);
1067     return pad_bcx.llbb;
1068 }
1069
1070 pub fn find_bcx_for_scope(bcx: @mut Block, scope_id: ast::NodeId) -> @mut Block {
1071     let mut bcx_sid = bcx;
1072     let mut cur_scope = bcx_sid.scope;
1073     loop {
1074         cur_scope = match cur_scope {
1075             Some(inf) => {
1076                 match inf.node_info {
1077                     Some(NodeInfo { id, _ }) if id == scope_id => {
1078                         return bcx_sid
1079                     }
1080                     // FIXME(#6268, #6248) hacky cleanup for nested method calls
1081                     Some(NodeInfo { callee_id: Some(id), _ }) if id == scope_id => {
1082                         return bcx_sid
1083                     }
1084                     _ => inf.parent
1085                 }
1086             }
1087             None => {
1088                 bcx_sid = match bcx_sid.parent {
1089                     None => bcx.tcx().sess.bug(fmt!("no enclosing scope with id %d", scope_id)),
1090                     Some(bcx_par) => bcx_par
1091                 };
1092                 bcx_sid.scope
1093             }
1094         }
1095     }
1096 }
1097
1098
1099 pub fn do_spill(bcx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1100     if ty::type_is_bot(t) {
1101         return C_null(Type::i8p());
1102     }
1103     let llptr = alloc_ty(bcx, t, "");
1104     Store(bcx, v, llptr);
1105     return llptr;
1106 }
1107
1108 // Since this function does *not* root, it is the caller's responsibility to
1109 // ensure that the referent is pointed to by a root.
1110 pub fn do_spill_noroot(cx: @mut Block, v: ValueRef) -> ValueRef {
1111     let llptr = alloca(cx, val_ty(v), "");
1112     Store(cx, v, llptr);
1113     return llptr;
1114 }
1115
1116 pub fn spill_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1117     let _icx = push_ctxt("spill_if_immediate");
1118     if ty::type_is_immediate(cx.tcx(), t) { return do_spill(cx, v, t); }
1119     return v;
1120 }
1121
1122 pub fn load_if_immediate(cx: @mut Block, v: ValueRef, t: ty::t) -> ValueRef {
1123     let _icx = push_ctxt("load_if_immediate");
1124     if ty::type_is_immediate(cx.tcx(), t) { return Load(cx, v); }
1125     return v;
1126 }
1127
1128 pub fn trans_trace(bcx: @mut Block, sp_opt: Option<Span>, trace_str: @str) {
1129     if !bcx.sess().trace() { return; }
1130     let _icx = push_ctxt("trans_trace");
1131     add_comment(bcx, trace_str);
1132     let V_trace_str = C_cstr(bcx.ccx(), trace_str);
1133     let (V_filename, V_line) = match sp_opt {
1134       Some(sp) => {
1135         let sess = bcx.sess();
1136         let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
1137         (C_cstr(bcx.ccx(), loc.file.name), loc.line as int)
1138       }
1139       None => {
1140         (C_cstr(bcx.ccx(), @"<runtime>"), 0)
1141       }
1142     };
1143     let ccx = bcx.ccx();
1144     let V_trace_str = PointerCast(bcx, V_trace_str, Type::i8p());
1145     let V_filename = PointerCast(bcx, V_filename, Type::i8p());
1146     let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
1147     Call(bcx, ccx.upcalls.trace, args, []);
1148 }
1149
1150 pub fn ignore_lhs(_bcx: @mut Block, local: &ast::Local) -> bool {
1151     match local.pat.node {
1152         ast::PatWild => true, _ => false
1153     }
1154 }
1155
1156 pub fn init_local(bcx: @mut Block, local: &ast::Local) -> @mut Block {
1157
1158     debug!("init_local(bcx=%s, local.id=%?)",
1159            bcx.to_str(), local.id);
1160     let _indenter = indenter();
1161
1162     let _icx = push_ctxt("init_local");
1163
1164     if ignore_lhs(bcx, local) {
1165         // Handle let _ = e; just like e;
1166         match local.init {
1167             Some(init) => {
1168               return expr::trans_into(bcx, init, expr::Ignore);
1169             }
1170             None => { return bcx; }
1171         }
1172     }
1173
1174     _match::store_local(bcx, local.pat, local.init)
1175 }
1176
1177 pub fn trans_stmt(cx: @mut Block, s: &ast::Stmt) -> @mut Block {
1178     let _icx = push_ctxt("trans_stmt");
1179     debug!("trans_stmt(%s)", stmt_to_str(s, cx.tcx().sess.intr()));
1180
1181     if cx.sess().asm_comments() {
1182         add_span_comment(cx, s.span, stmt_to_str(s, cx.ccx().sess.intr()));
1183     }
1184
1185     let mut bcx = cx;
1186
1187     match s.node {
1188         ast::StmtExpr(e, _) | ast::StmtSemi(e, _) => {
1189             bcx = expr::trans_into(cx, e, expr::Ignore);
1190         }
1191         ast::StmtDecl(d, _) => {
1192             match d.node {
1193                 ast::DeclLocal(ref local) => {
1194                     bcx = init_local(bcx, *local);
1195                     if cx.sess().opts.extra_debuginfo {
1196                         debuginfo::create_local_var_metadata(bcx, *local);
1197                     }
1198                 }
1199                 ast::DeclItem(i) => trans_item(cx.fcx.ccx, i)
1200             }
1201         }
1202         ast::StmtMac(*) => cx.tcx().sess.bug("unexpanded macro")
1203     }
1204
1205     return bcx;
1206 }
1207
1208 // You probably don't want to use this one. See the
1209 // next three functions instead.
1210 pub fn new_block(cx: @mut FunctionContext,
1211                  parent: Option<@mut Block>,
1212                  scope: Option<@mut ScopeInfo>,
1213                  is_lpad: bool,
1214                  name: &str,
1215                  opt_node_info: Option<NodeInfo>)
1216               -> @mut Block {
1217     unsafe {
1218         let llbb = do name.with_c_str |buf| {
1219             llvm::LLVMAppendBasicBlockInContext(cx.ccx.llcx, cx.llfn, buf)
1220         };
1221         let bcx = @mut Block::new(llbb,
1222                                   parent,
1223                                   is_lpad,
1224                                   opt_node_info,
1225                                   cx);
1226         bcx.scope = scope;
1227         for cx in parent.iter() {
1228             if cx.unreachable {
1229                 Unreachable(bcx);
1230                 break;
1231             }
1232         }
1233         bcx
1234     }
1235 }
1236
1237 pub fn simple_block_scope(parent: Option<@mut ScopeInfo>,
1238                           node_info: Option<NodeInfo>) -> @mut ScopeInfo {
1239     @mut ScopeInfo {
1240         parent: parent,
1241         loop_break: None,
1242         loop_label: None,
1243         cleanups: ~[],
1244         cleanup_paths: ~[],
1245         landing_pad: None,
1246         node_info: node_info,
1247     }
1248 }
1249
1250 // Use this when you're at the top block of a function or the like.
1251 pub fn top_scope_block(fcx: @mut FunctionContext, opt_node_info: Option<NodeInfo>)
1252                     -> @mut Block {
1253     return new_block(fcx, None, Some(simple_block_scope(None, opt_node_info)), false,
1254                   "function top level", opt_node_info);
1255 }
1256
1257 pub fn scope_block(bcx: @mut Block,
1258                    opt_node_info: Option<NodeInfo>,
1259                    n: &str) -> @mut Block {
1260     return new_block(bcx.fcx, Some(bcx), Some(simple_block_scope(None, opt_node_info)), bcx.is_lpad,
1261                   n, opt_node_info);
1262 }
1263
1264 pub fn loop_scope_block(bcx: @mut Block,
1265                         loop_break: @mut Block,
1266                         loop_label: Option<Name>,
1267                         n: &str,
1268                         opt_node_info: Option<NodeInfo>) -> @mut Block {
1269     return new_block(bcx.fcx, Some(bcx), Some(@mut ScopeInfo {
1270         parent: None,
1271         loop_break: Some(loop_break),
1272         loop_label: loop_label,
1273         cleanups: ~[],
1274         cleanup_paths: ~[],
1275         landing_pad: None,
1276         node_info: opt_node_info,
1277     }), bcx.is_lpad, n, opt_node_info);
1278 }
1279
1280 // Use this when creating a block for the inside of a landing pad.
1281 pub fn lpad_block(bcx: @mut Block, n: &str) -> @mut Block {
1282     new_block(bcx.fcx, Some(bcx), None, true, n, None)
1283 }
1284
1285 // Use this when you're making a general CFG BB within a scope.
1286 pub fn sub_block(bcx: @mut Block, n: &str) -> @mut Block {
1287     new_block(bcx.fcx, Some(bcx), None, bcx.is_lpad, n, None)
1288 }
1289
1290 pub fn raw_block(fcx: @mut FunctionContext, is_lpad: bool, llbb: BasicBlockRef) -> @mut Block {
1291     @mut Block::new(llbb, None, is_lpad, None, fcx)
1292 }
1293
1294
1295 // trans_block_cleanups: Go through all the cleanups attached to this
1296 // block and execute them.
1297 //
1298 // When translating a block that introduces new variables during its scope, we
1299 // need to make sure those variables go out of scope when the block ends.  We
1300 // do that by running a 'cleanup' function for each variable.
1301 // trans_block_cleanups runs all the cleanup functions for the block.
1302 pub fn trans_block_cleanups(bcx: @mut Block, cleanups: ~[cleanup]) -> @mut Block {
1303     trans_block_cleanups_(bcx, cleanups, false)
1304 }
1305
1306 pub fn trans_block_cleanups_(bcx: @mut Block,
1307                              cleanups: &[cleanup],
1308                              /* cleanup_cx: block, */
1309                              is_lpad: bool) -> @mut Block {
1310     let _icx = push_ctxt("trans_block_cleanups");
1311     // NB: Don't short-circuit even if this block is unreachable because
1312     // GC-based cleanup needs to the see that the roots are live.
1313     let no_lpads =
1314         bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0;
1315     if bcx.unreachable && !no_lpads { return bcx; }
1316     let mut bcx = bcx;
1317     for cu in cleanups.rev_iter() {
1318         match *cu {
1319             clean(cfn, cleanup_type) | clean_temp(_, cfn, cleanup_type) => {
1320                 // Some types don't need to be cleaned up during
1321                 // landing pads because they can be freed en mass later
1322                 if cleanup_type == normal_exit_and_unwind || !is_lpad {
1323                     bcx = cfn(bcx);
1324                 }
1325             }
1326         }
1327     }
1328     return bcx;
1329 }
1330
1331 // In the last argument, Some(block) mean jump to this block, and none means
1332 // this is a landing pad and leaving should be accomplished with a resume
1333 // instruction.
1334 pub fn cleanup_and_leave(bcx: @mut Block,
1335                          upto: Option<BasicBlockRef>,
1336                          leave: Option<BasicBlockRef>) {
1337     let _icx = push_ctxt("cleanup_and_leave");
1338     let mut cur = bcx;
1339     let mut bcx = bcx;
1340     let is_lpad = leave == None;
1341     loop {
1342         debug!("cleanup_and_leave: leaving %s", cur.to_str());
1343
1344         if bcx.sess().trace() {
1345             trans_trace(
1346                 bcx, None,
1347                 (fmt!("cleanup_and_leave(%s)", cur.to_str())).to_managed());
1348         }
1349
1350         let mut cur_scope = cur.scope;
1351         loop {
1352             cur_scope = match cur_scope {
1353                 Some (inf) if !inf.empty_cleanups() => {
1354                     let (sub_cx, dest, inf_cleanups) = {
1355                         let inf = &mut *inf;
1356                         let mut skip = 0;
1357                         let mut dest = None;
1358                         {
1359                             let r = (*inf).cleanup_paths.rev_iter().find(|cp| cp.target == leave);
1360                             for cp in r.iter() {
1361                                 if cp.size == inf.cleanups.len() {
1362                                     Br(bcx, cp.dest);
1363                                     return;
1364                                 }
1365
1366                                 skip = cp.size;
1367                                 dest = Some(cp.dest);
1368                             }
1369                         }
1370                         let sub_cx = sub_block(bcx, "cleanup");
1371                         Br(bcx, sub_cx.llbb);
1372                         inf.cleanup_paths.push(cleanup_path {
1373                             target: leave,
1374                             size: inf.cleanups.len(),
1375                             dest: sub_cx.llbb
1376                         });
1377                         (sub_cx, dest, inf.cleanups.tailn(skip).to_owned())
1378                     };
1379                     bcx = trans_block_cleanups_(sub_cx,
1380                                                 inf_cleanups,
1381                                                 is_lpad);
1382                     for &dest in dest.iter() {
1383                         Br(bcx, dest);
1384                         return;
1385                     }
1386                     inf.parent
1387                 }
1388                 Some(inf) => inf.parent,
1389                 None => break
1390             }
1391         }
1392
1393         match upto {
1394           Some(bb) => { if cur.llbb == bb { break; } }
1395           _ => ()
1396         }
1397         cur = match cur.parent {
1398           Some(next) => next,
1399           None => { assert!(upto.is_none()); break; }
1400         };
1401     }
1402     match leave {
1403       Some(target) => Br(bcx, target),
1404       None => { Resume(bcx, Load(bcx, bcx.fcx.personality.unwrap())); }
1405     }
1406 }
1407
1408 pub fn cleanup_block(bcx: @mut Block, upto: Option<BasicBlockRef>) -> @mut Block{
1409     let _icx = push_ctxt("cleanup_block");
1410     let mut cur = bcx;
1411     let mut bcx = bcx;
1412     loop {
1413         debug!("cleanup_block: %s", cur.to_str());
1414
1415         if bcx.sess().trace() {
1416             trans_trace(
1417                 bcx, None,
1418                 (fmt!("cleanup_block(%s)", cur.to_str())).to_managed());
1419         }
1420
1421         let mut cur_scope = cur.scope;
1422         loop {
1423             cur_scope = match cur_scope {
1424                 Some (inf) => {
1425                     bcx = trans_block_cleanups_(bcx, inf.cleanups.to_owned(), false);
1426                     inf.parent
1427                 }
1428                 None => break
1429             }
1430         }
1431
1432         match upto {
1433           Some(bb) => { if cur.llbb == bb { break; } }
1434           _ => ()
1435         }
1436         cur = match cur.parent {
1437           Some(next) => next,
1438           None => { assert!(upto.is_none()); break; }
1439         };
1440     }
1441     bcx
1442 }
1443
1444 pub fn cleanup_and_Br(bcx: @mut Block, upto: @mut Block, target: BasicBlockRef) {
1445     let _icx = push_ctxt("cleanup_and_Br");
1446     cleanup_and_leave(bcx, Some(upto.llbb), Some(target));
1447 }
1448
1449 pub fn leave_block(bcx: @mut Block, out_of: @mut Block) -> @mut Block {
1450     let _icx = push_ctxt("leave_block");
1451     let next_cx = sub_block(block_parent(out_of), "next");
1452     if bcx.unreachable { Unreachable(next_cx); }
1453     cleanup_and_Br(bcx, out_of, next_cx.llbb);
1454     next_cx
1455 }
1456
1457 pub fn with_scope(bcx: @mut Block,
1458                   opt_node_info: Option<NodeInfo>,
1459                   name: &str,
1460                   f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1461     let _icx = push_ctxt("with_scope");
1462
1463     debug!("with_scope(bcx=%s, opt_node_info=%?, name=%s)",
1464            bcx.to_str(), opt_node_info, name);
1465     let _indenter = indenter();
1466
1467     let scope = simple_block_scope(bcx.scope, opt_node_info);
1468     bcx.scope = Some(scope);
1469     let ret = f(bcx);
1470     let ret = trans_block_cleanups_(ret, (scope.cleanups).clone(), false);
1471     bcx.scope = scope.parent;
1472     ret
1473 }
1474
1475 pub fn with_scope_result(bcx: @mut Block,
1476                          opt_node_info: Option<NodeInfo>,
1477                          _name: &str,
1478                          f: &fn(@mut Block) -> Result) -> Result {
1479     let _icx = push_ctxt("with_scope_result");
1480
1481     let scope = simple_block_scope(bcx.scope, opt_node_info);
1482     bcx.scope = Some(scope);
1483     let Result { bcx: out_bcx, val } = f(bcx);
1484     let out_bcx = trans_block_cleanups_(out_bcx,
1485                                         (scope.cleanups).clone(),
1486                                         false);
1487     bcx.scope = scope.parent;
1488
1489     rslt(out_bcx, val)
1490 }
1491
1492 pub fn with_scope_datumblock(bcx: @mut Block, opt_node_info: Option<NodeInfo>,
1493                              name: &str, f: &fn(@mut Block) -> datum::DatumBlock)
1494                           -> datum::DatumBlock {
1495     use middle::trans::datum::DatumBlock;
1496
1497     let _icx = push_ctxt("with_scope_result");
1498     let scope_cx = scope_block(bcx, opt_node_info, name);
1499     Br(bcx, scope_cx.llbb);
1500     let DatumBlock {bcx, datum} = f(scope_cx);
1501     DatumBlock {bcx: leave_block(bcx, scope_cx), datum: datum}
1502 }
1503
1504 pub fn block_locals(b: &ast::Block, it: &fn(@ast::Local)) {
1505     for s in b.stmts.iter() {
1506         match s.node {
1507           ast::StmtDecl(d, _) => {
1508             match d.node {
1509               ast::DeclLocal(ref local) => it(*local),
1510               _ => {} /* fall through */
1511             }
1512           }
1513           _ => {} /* fall through */
1514         }
1515     }
1516 }
1517
1518 pub fn with_cond(bcx: @mut Block, val: ValueRef, f: &fn(@mut Block) -> @mut Block) -> @mut Block {
1519     let _icx = push_ctxt("with_cond");
1520     let next_cx = base::sub_block(bcx, "next");
1521     let cond_cx = base::sub_block(bcx, "cond");
1522     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1523     let after_cx = f(cond_cx);
1524     if !after_cx.terminated { Br(after_cx, next_cx.llbb); }
1525     next_cx
1526 }
1527
1528 pub fn call_memcpy(cx: @mut Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1529     let _icx = push_ctxt("call_memcpy");
1530     let ccx = cx.ccx();
1531     let key = match ccx.sess.targ_cfg.arch {
1532         X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1533         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1534     };
1535     let memcpy = ccx.intrinsics.get_copy(&key);
1536     let src_ptr = PointerCast(cx, src, Type::i8p());
1537     let dst_ptr = PointerCast(cx, dst, Type::i8p());
1538     let size = IntCast(cx, n_bytes, ccx.int_type);
1539     let align = C_i32(align as i32);
1540     let volatile = C_i1(false);
1541     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1542 }
1543
1544 pub fn memcpy_ty(bcx: @mut Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1545     let _icx = push_ctxt("memcpy_ty");
1546     let ccx = bcx.ccx();
1547     if ty::type_is_structural(t) {
1548         let llty = type_of::type_of(ccx, t);
1549         let llsz = llsize_of(ccx, llty);
1550         let llalign = llalign_of_min(ccx, llty);
1551         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1552     } else {
1553         Store(bcx, Load(bcx, src), dst);
1554     }
1555 }
1556
1557 pub fn zero_mem(cx: @mut Block, llptr: ValueRef, t: ty::t) {
1558     if cx.unreachable { return; }
1559     let _icx = push_ctxt("zero_mem");
1560     let bcx = cx;
1561     let ccx = cx.ccx();
1562     let llty = type_of::type_of(ccx, t);
1563     memzero(&B(bcx), llptr, llty);
1564 }
1565
1566 // Always use this function instead of storing a zero constant to the memory
1567 // in question. If you store a zero constant, LLVM will drown in vreg
1568 // allocation for large data structures, and the generated code will be
1569 // awful. (A telltale sign of this is large quantities of
1570 // `mov [byte ptr foo],0` in the generated code.)
1571 pub fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1572     let _icx = push_ctxt("memzero");
1573     let ccx = b.ccx;
1574
1575     let intrinsic_key = match ccx.sess.targ_cfg.arch {
1576         X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1577         X86_64 => "llvm.memset.p0i8.i64"
1578     };
1579
1580     let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1581     let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1582     let llzeroval = C_u8(0);
1583     let size = machine::llsize_of(ccx, ty);
1584     let align = C_i32(llalign_of_min(ccx, ty) as i32);
1585     let volatile = C_i1(false);
1586     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1587 }
1588
1589 pub fn alloc_ty(bcx: @mut Block, t: ty::t, name: &str) -> ValueRef {
1590     let _icx = push_ctxt("alloc_ty");
1591     let ccx = bcx.ccx();
1592     let ty = type_of::type_of(ccx, t);
1593     assert!(!ty::type_has_params(t), "Type has params: %s", ty_to_str(ccx.tcx, t));
1594     let val = alloca(bcx, ty, name);
1595     return val;
1596 }
1597
1598 pub fn alloca(cx: @mut Block, ty: Type, name: &str) -> ValueRef {
1599     alloca_maybe_zeroed(cx, ty, name, false)
1600 }
1601
1602 pub fn alloca_maybe_zeroed(cx: @mut Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1603     let _icx = push_ctxt("alloca");
1604     if cx.unreachable {
1605         unsafe {
1606             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1607         }
1608     }
1609     let p = Alloca(cx, ty, name);
1610     if zero {
1611         let b = cx.fcx.ccx.builder();
1612         b.position_before(cx.fcx.alloca_insert_pt.unwrap());
1613         memzero(&b, p, ty);
1614     }
1615     p
1616 }
1617
1618 pub fn arrayalloca(cx: @mut Block, ty: Type, v: ValueRef) -> ValueRef {
1619     let _icx = push_ctxt("arrayalloca");
1620     if cx.unreachable {
1621         unsafe {
1622             return llvm::LLVMGetUndef(ty.to_ref());
1623         }
1624     }
1625     return ArrayAlloca(cx, ty, v);
1626 }
1627
1628 pub struct BasicBlocks {
1629     sa: BasicBlockRef,
1630 }
1631
1632 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1633     unsafe {
1634         let cx = task_llcx();
1635         do "static_allocas".with_c_str | buf| {
1636             llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1637         }
1638     }
1639 }
1640
1641 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1642     unsafe {
1643         let cx = task_llcx();
1644         do "return".with_c_str |buf| {
1645             llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1646         }
1647     }
1648 }
1649
1650 // Creates and returns space for, or returns the argument representing, the
1651 // slot where the return value of the function must go.
1652 pub fn make_return_pointer(fcx: @mut FunctionContext, output_type: ty::t) -> ValueRef {
1653     unsafe {
1654         if type_of::return_uses_outptr(fcx.ccx.tcx, output_type) {
1655             llvm::LLVMGetParam(fcx.llfn, 0)
1656         } else {
1657             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1658             let bcx = fcx.entry_bcx.unwrap();
1659             Alloca(bcx, lloutputtype, "__make_return_pointer")
1660         }
1661     }
1662 }
1663
1664 // NB: must keep 4 fns in sync:
1665 //
1666 //  - type_of_fn
1667 //  - create_llargs_for_fn_args.
1668 //  - new_fn_ctxt
1669 //  - trans_args
1670 pub fn new_fn_ctxt_w_id(ccx: @mut CrateContext,
1671                         path: path,
1672                         llfndecl: ValueRef,
1673                         id: ast::NodeId,
1674                         output_type: ty::t,
1675                         skip_retptr: bool,
1676                         param_substs: Option<@param_substs>,
1677                         opt_node_info: Option<NodeInfo>,
1678                         sp: Option<Span>)
1679                      -> @mut FunctionContext {
1680     for p in param_substs.iter() { p.validate(); }
1681
1682     debug!("new_fn_ctxt_w_id(path=%s, id=%?, \
1683             param_substs=%s)",
1684            path_str(ccx.sess, path),
1685            id,
1686            param_substs.repr(ccx.tcx));
1687
1688     let substd_output_type = match param_substs {
1689         None => output_type,
1690         Some(substs) => {
1691             ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1692         }
1693     };
1694     let uses_outptr = type_of::return_uses_outptr(ccx.tcx, substd_output_type);
1695     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1696
1697     let fcx = @mut FunctionContext {
1698           llfn: llfndecl,
1699           llenv: unsafe {
1700               llvm::LLVMGetUndef(Type::i8p().to_ref())
1701           },
1702           llretptr: None,
1703           entry_bcx: None,
1704           alloca_insert_pt: None,
1705           llreturn: None,
1706           llself: None,
1707           personality: None,
1708           caller_expects_out_pointer: uses_outptr,
1709           llargs: @mut HashMap::new(),
1710           lllocals: @mut HashMap::new(),
1711           llupvars: @mut HashMap::new(),
1712           id: id,
1713           param_substs: param_substs,
1714           span: sp,
1715           path: path,
1716           ccx: ccx,
1717           debug_context: debug_context,
1718     };
1719     fcx.llenv = unsafe {
1720           llvm::LLVMGetParam(llfndecl, fcx.env_arg_pos() as c_uint)
1721     };
1722
1723     unsafe {
1724         let entry_bcx = top_scope_block(fcx, opt_node_info);
1725         Load(entry_bcx, C_null(Type::i8p()));
1726
1727         fcx.entry_bcx = Some(entry_bcx);
1728         fcx.alloca_insert_pt = Some(llvm::LLVMGetFirstInstruction(entry_bcx.llbb));
1729     }
1730
1731     if !ty::type_is_voidish(substd_output_type) {
1732         // If the function returns nil/bot, there is no real return
1733         // value, so do not set `llretptr`.
1734         if !skip_retptr || uses_outptr {
1735             // Otherwise, we normally allocate the llretptr, unless we
1736             // have been instructed to skip it for immediate return
1737             // values.
1738             fcx.llretptr = Some(make_return_pointer(fcx, substd_output_type));
1739         }
1740     }
1741     fcx
1742 }
1743
1744 pub fn new_fn_ctxt(ccx: @mut CrateContext,
1745                    path: path,
1746                    llfndecl: ValueRef,
1747                    output_type: ty::t,
1748                    sp: Option<Span>)
1749                 -> @mut FunctionContext {
1750     new_fn_ctxt_w_id(ccx, path, llfndecl, -1, output_type, false, None, None, sp)
1751 }
1752
1753 // NB: must keep 4 fns in sync:
1754 //
1755 //  - type_of_fn
1756 //  - create_llargs_for_fn_args.
1757 //  - new_fn_ctxt
1758 //  - trans_args
1759
1760 // create_llargs_for_fn_args: Creates a mapping from incoming arguments to
1761 // allocas created for them.
1762 //
1763 // When we translate a function, we need to map its incoming arguments to the
1764 // spaces that have been created for them (by code in the llallocas field of
1765 // the function's fn_ctxt).  create_llargs_for_fn_args populates the llargs
1766 // field of the fn_ctxt with
1767 pub fn create_llargs_for_fn_args(cx: @mut FunctionContext,
1768                                  self_arg: self_arg,
1769                                  args: &[ast::arg])
1770                               -> ~[ValueRef] {
1771     let _icx = push_ctxt("create_llargs_for_fn_args");
1772
1773     match self_arg {
1774       impl_self(tt, self_mode) => {
1775         cx.llself = Some(ValSelfData {
1776             v: cx.llenv,
1777             t: tt,
1778             is_copy: self_mode == ty::ByCopy
1779         });
1780       }
1781       no_self => ()
1782     }
1783
1784     // Return an array containing the ValueRefs that we get from
1785     // llvm::LLVMGetParam for each argument.
1786     do vec::from_fn(args.len()) |i| {
1787         unsafe { llvm::LLVMGetParam(cx.llfn, cx.arg_pos(i) as c_uint) }
1788     }
1789 }
1790
1791 pub fn copy_args_to_allocas(fcx: @mut FunctionContext,
1792                             bcx: @mut Block,
1793                             args: &[ast::arg],
1794                             raw_llargs: &[ValueRef],
1795                             arg_tys: &[ty::t]) -> @mut Block {
1796     debug!("copy_args_to_allocas: raw_llargs=%s arg_tys=%s",
1797            raw_llargs.llrepr(fcx.ccx),
1798            arg_tys.repr(fcx.ccx.tcx));
1799
1800     let _icx = push_ctxt("copy_args_to_allocas");
1801     let mut bcx = bcx;
1802
1803     match fcx.llself {
1804         Some(slf) => {
1805             let self_val = if slf.is_copy
1806                     && datum::appropriate_mode(bcx.tcx(), slf.t).is_by_value() {
1807                 let tmp = BitCast(bcx, slf.v, type_of(bcx.ccx(), slf.t));
1808                 let alloc = alloc_ty(bcx, slf.t, "__self");
1809                 Store(bcx, tmp, alloc);
1810                 alloc
1811             } else {
1812                 PointerCast(bcx, slf.v, type_of(bcx.ccx(), slf.t).ptr_to())
1813             };
1814
1815             fcx.llself = Some(ValSelfData {v: self_val, ..slf});
1816             add_clean(bcx, self_val, slf.t);
1817
1818             if fcx.ccx.sess.opts.extra_debuginfo {
1819                 debuginfo::create_self_argument_metadata(bcx, slf.t, self_val);
1820             }
1821         }
1822         _ => {}
1823     }
1824
1825     for (arg_n, &arg_ty) in arg_tys.iter().enumerate() {
1826         let raw_llarg = raw_llargs[arg_n];
1827
1828         // For certain mode/type combinations, the raw llarg values are passed
1829         // by value.  However, within the fn body itself, we want to always
1830         // have all locals and arguments be by-ref so that we can cancel the
1831         // cleanup and for better interaction with LLVM's debug info.  So, if
1832         // the argument would be passed by value, we store it into an alloca.
1833         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1834         // the event it's not truly needed.
1835         // only by value if immediate:
1836         let llarg = if datum::appropriate_mode(bcx.tcx(), arg_ty).is_by_value() {
1837             let alloc = alloc_ty(bcx, arg_ty, "__arg");
1838             Store(bcx, raw_llarg, alloc);
1839             alloc
1840         } else {
1841             raw_llarg
1842         };
1843         bcx = _match::store_arg(bcx, args[arg_n].pat, llarg);
1844
1845         if fcx.ccx.sess.opts.extra_debuginfo {
1846             debuginfo::create_argument_metadata(bcx, &args[arg_n]);
1847         }
1848     }
1849
1850     return bcx;
1851 }
1852
1853 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1854 // and builds the return block.
1855 pub fn finish_fn(fcx: @mut FunctionContext, last_bcx: @mut Block) {
1856     let _icx = push_ctxt("finish_fn");
1857
1858     let ret_cx = match fcx.llreturn {
1859         Some(llreturn) => {
1860             if !last_bcx.terminated {
1861                 Br(last_bcx, llreturn);
1862             }
1863             raw_block(fcx, false, llreturn)
1864         }
1865         None => last_bcx
1866     };
1867     build_return_block(fcx, ret_cx);
1868     fcx.cleanup();
1869 }
1870
1871 // Builds the return block for a function.
1872 pub fn build_return_block(fcx: &FunctionContext, ret_cx: @mut Block) {
1873     // Return the value if this function immediate; otherwise, return void.
1874     if fcx.llretptr.is_none() || fcx.caller_expects_out_pointer {
1875         return RetVoid(ret_cx);
1876     }
1877
1878     let retptr = Value(fcx.llretptr.unwrap());
1879     let retval = match retptr.get_dominating_store(ret_cx) {
1880         // If there's only a single store to the ret slot, we can directly return
1881         // the value that was stored and omit the store and the alloca
1882         Some(s) => {
1883             let retval = *s.get_operand(0).unwrap();
1884             s.erase_from_parent();
1885
1886             if retptr.has_no_uses() {
1887                 retptr.erase_from_parent();
1888             }
1889
1890             retval
1891         }
1892         // Otherwise, load the return value from the ret slot
1893         None => Load(ret_cx, fcx.llretptr.unwrap())
1894     };
1895
1896
1897     Ret(ret_cx, retval);
1898 }
1899
1900 pub enum self_arg { impl_self(ty::t, ty::SelfMode), no_self, }
1901
1902 // trans_closure: Builds an LLVM function out of a source function.
1903 // If the function closes over its environment a closure will be
1904 // returned.
1905 pub fn trans_closure(ccx: @mut CrateContext,
1906                      path: path,
1907                      decl: &ast::fn_decl,
1908                      body: &ast::Block,
1909                      llfndecl: ValueRef,
1910                      self_arg: self_arg,
1911                      param_substs: Option<@param_substs>,
1912                      id: ast::NodeId,
1913                      attributes: &[ast::Attribute],
1914                      output_type: ty::t,
1915                      maybe_load_env: &fn(@mut FunctionContext)) {
1916     ccx.stats.n_closures += 1;
1917     let _icx = push_ctxt("trans_closure");
1918     set_uwtable(llfndecl);
1919
1920     debug!("trans_closure(..., param_substs=%s)",
1921            param_substs.repr(ccx.tcx));
1922
1923     let fcx = new_fn_ctxt_w_id(ccx,
1924                                path,
1925                                llfndecl,
1926                                id,
1927                                output_type,
1928                                false,
1929                                param_substs,
1930                                body.info(),
1931                                Some(body.span));
1932
1933     // Create the first basic block in the function and keep a handle on it to
1934     //  pass to finish_fn later.
1935     let bcx_top = fcx.entry_bcx.unwrap();
1936     let mut bcx = bcx_top;
1937     let block_ty = node_id_type(bcx, body.id);
1938
1939     // Set up arguments to the function.
1940     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1941     let raw_llargs = create_llargs_for_fn_args(fcx, self_arg, decl.inputs);
1942
1943     // Set the fixed stack segment flag if necessary.
1944     if attr::contains_name(attributes, "fixed_stack_segment") {
1945         set_no_inline(fcx.llfn);
1946         set_fixed_stack_segment(fcx.llfn);
1947     }
1948
1949     bcx = copy_args_to_allocas(fcx, bcx, decl.inputs, raw_llargs, arg_tys);
1950
1951     maybe_load_env(fcx);
1952
1953     // Up until here, IR instructions for this function have explicitly not been annotated with
1954     // source code location, so we don't step into call setup code. From here on, source location
1955     // emitting should be enabled.
1956     debuginfo::start_emitting_source_locations(fcx);
1957
1958     // This call to trans_block is the place where we bridge between
1959     // translation calls that don't have a return value (trans_crate,
1960     // trans_mod, trans_item, et cetera) and those that do
1961     // (trans_block, trans_expr, et cetera).
1962     if body.expr.is_none() || ty::type_is_voidish(block_ty) {
1963         bcx = controlflow::trans_block(bcx, body, expr::Ignore);
1964     } else {
1965         let dest = expr::SaveIn(fcx.llretptr.unwrap());
1966         bcx = controlflow::trans_block(bcx, body, dest);
1967     }
1968
1969     match fcx.llreturn {
1970         Some(llreturn) => cleanup_and_Br(bcx, bcx_top, llreturn),
1971         None => bcx = cleanup_block(bcx, Some(bcx_top.llbb))
1972     };
1973
1974     // Put return block after all other blocks.
1975     // This somewhat improves single-stepping experience in debugger.
1976     unsafe {
1977         for &llreturn in fcx.llreturn.iter() {
1978             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1979         }
1980     }
1981
1982     // Insert the mandatory first few basic blocks before lltop.
1983     finish_fn(fcx, bcx);
1984 }
1985
1986 // trans_fn: creates an LLVM function corresponding to a source language
1987 // function.
1988 pub fn trans_fn(ccx: @mut CrateContext,
1989                 path: path,
1990                 decl: &ast::fn_decl,
1991                 body: &ast::Block,
1992                 llfndecl: ValueRef,
1993                 self_arg: self_arg,
1994                 param_substs: Option<@param_substs>,
1995                 id: ast::NodeId,
1996                 attrs: &[ast::Attribute]) {
1997
1998     let the_path_str = path_str(ccx.sess, path);
1999     let _s = StatRecorder::new(ccx, the_path_str);
2000     debug!("trans_fn(self_arg=%?, param_substs=%s)",
2001            self_arg,
2002            param_substs.repr(ccx.tcx));
2003     let _icx = push_ctxt("trans_fn");
2004     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
2005     trans_closure(ccx,
2006                   path.clone(),
2007                   decl,
2008                   body,
2009                   llfndecl,
2010                   self_arg,
2011                   param_substs,
2012                   id,
2013                   attrs,
2014                   output_type,
2015                   |_fcx| { });
2016 }
2017
2018 fn insert_synthetic_type_entries(bcx: @mut Block,
2019                                  fn_args: &[ast::arg],
2020                                  arg_tys: &[ty::t])
2021 {
2022     /*!
2023      * For tuple-like structs and enum-variants, we generate
2024      * synthetic AST nodes for the arguments.  These have no types
2025      * in the type table and no entries in the moves table,
2026      * so the code in `copy_args_to_allocas` and `bind_irrefutable_pat`
2027      * gets upset. This hack of a function bridges the gap by inserting types.
2028      *
2029      * This feels horrible. I think we should just have a special path
2030      * for these functions and not try to use the generic code, but
2031      * that's not the problem I'm trying to solve right now. - nmatsakis
2032      */
2033
2034     let tcx = bcx.tcx();
2035     for i in range(0u, fn_args.len()) {
2036         debug!("setting type of argument %u (pat node %d) to %s",
2037                i, fn_args[i].pat.id, bcx.ty_to_str(arg_tys[i]));
2038
2039         let pat_id = fn_args[i].pat.id;
2040         let arg_ty = arg_tys[i];
2041         tcx.node_types.insert(pat_id as uint, arg_ty);
2042     }
2043 }
2044
2045 pub fn trans_enum_variant(ccx: @mut CrateContext,
2046                           _enum_id: ast::NodeId,
2047                           variant: &ast::variant,
2048                           args: &[ast::variant_arg],
2049                           disr: ty::Disr,
2050                           param_substs: Option<@param_substs>,
2051                           llfndecl: ValueRef) {
2052     let _icx = push_ctxt("trans_enum_variant");
2053
2054     trans_enum_variant_or_tuple_like_struct(
2055         ccx,
2056         variant.node.id,
2057         args,
2058         disr,
2059         param_substs,
2060         llfndecl);
2061 }
2062
2063 pub fn trans_tuple_struct(ccx: @mut CrateContext,
2064                           fields: &[@ast::struct_field],
2065                           ctor_id: ast::NodeId,
2066                           param_substs: Option<@param_substs>,
2067                           llfndecl: ValueRef) {
2068     let _icx = push_ctxt("trans_tuple_struct");
2069
2070     trans_enum_variant_or_tuple_like_struct(
2071         ccx,
2072         ctor_id,
2073         fields,
2074         0,
2075         param_substs,
2076         llfndecl);
2077 }
2078
2079 trait IdAndTy {
2080     fn id(&self) -> ast::NodeId;
2081     fn ty<'a>(&'a self) -> &'a ast::Ty;
2082 }
2083
2084 impl IdAndTy for ast::variant_arg {
2085     fn id(&self) -> ast::NodeId { self.id }
2086     fn ty<'a>(&'a self) -> &'a ast::Ty { &self.ty }
2087 }
2088
2089 impl IdAndTy for @ast::struct_field {
2090     fn id(&self) -> ast::NodeId { self.node.id }
2091     fn ty<'a>(&'a self) -> &'a ast::Ty { &self.node.ty }
2092 }
2093
2094 pub fn trans_enum_variant_or_tuple_like_struct<A:IdAndTy>(
2095     ccx: @mut CrateContext,
2096     ctor_id: ast::NodeId,
2097     args: &[A],
2098     disr: ty::Disr,
2099     param_substs: Option<@param_substs>,
2100     llfndecl: ValueRef)
2101 {
2102     // Translate variant arguments to function arguments.
2103     let fn_args = do args.map |varg| {
2104         ast::arg {
2105             is_mutbl: false,
2106             ty: (*varg.ty()).clone(),
2107             pat: ast_util::ident_to_pat(
2108                 ccx.tcx.sess.next_node_id(),
2109                 codemap::dummy_sp(),
2110                 special_idents::arg),
2111             id: varg.id(),
2112         }
2113     };
2114
2115     let no_substs: &[ty::t] = [];
2116     let ty_param_substs = match param_substs {
2117         Some(ref substs) => {
2118             let v: &[ty::t] = substs.tys;
2119             v
2120         }
2121         None => {
2122             let v: &[ty::t] = no_substs;
2123             v
2124         }
2125     };
2126
2127     let ctor_ty = ty::subst_tps(ccx.tcx,
2128                                 ty_param_substs,
2129                                 None,
2130                                 ty::node_id_to_type(ccx.tcx, ctor_id));
2131
2132     let result_ty = match ty::get(ctor_ty).sty {
2133         ty::ty_bare_fn(ref bft) => bft.sig.output,
2134         _ => ccx.sess.bug(
2135             fmt!("trans_enum_variant_or_tuple_like_struct: \
2136                   unexpected ctor return type %s",
2137                  ty_to_str(ccx.tcx, ctor_ty)))
2138     };
2139
2140     let fcx = new_fn_ctxt_w_id(ccx,
2141                                ~[],
2142                                llfndecl,
2143                                ctor_id,
2144                                result_ty,
2145                                false,
2146                                param_substs,
2147                                None,
2148                                None);
2149
2150     let arg_tys = ty::ty_fn_args(ctor_ty);
2151
2152     let raw_llargs = create_llargs_for_fn_args(fcx, no_self, fn_args);
2153
2154     let bcx = fcx.entry_bcx.unwrap();
2155
2156     insert_synthetic_type_entries(bcx, fn_args, arg_tys);
2157     let bcx = copy_args_to_allocas(fcx, bcx, fn_args, raw_llargs, arg_tys);
2158
2159     let repr = adt::represent_type(ccx, result_ty);
2160     adt::trans_start_init(bcx, repr, fcx.llretptr.unwrap(), disr);
2161     for (i, fn_arg) in fn_args.iter().enumerate() {
2162         let lldestptr = adt::trans_field_ptr(bcx,
2163                                              repr,
2164                                              fcx.llretptr.unwrap(),
2165                                              disr,
2166                                              i);
2167         let llarg = fcx.llargs.get_copy(&fn_arg.pat.id);
2168         let arg_ty = arg_tys[i];
2169         memcpy_ty(bcx, lldestptr, llarg, arg_ty);
2170     }
2171     finish_fn(fcx, bcx);
2172 }
2173
2174 pub fn trans_enum_def(ccx: @mut CrateContext, enum_definition: &ast::enum_def,
2175                       id: ast::NodeId, vi: @~[@ty::VariantInfo],
2176                       i: &mut uint) {
2177     for variant in enum_definition.variants.iter() {
2178         let disr_val = vi[*i].disr_val;
2179         *i += 1;
2180
2181         match variant.node.kind {
2182             ast::tuple_variant_kind(ref args) if args.len() > 0 => {
2183                 let llfn = get_item_val(ccx, variant.node.id);
2184                 trans_enum_variant(ccx, id, variant, *args,
2185                                    disr_val, None, llfn);
2186             }
2187             ast::tuple_variant_kind(_) => {
2188                 // Nothing to do.
2189             }
2190             ast::struct_variant_kind(struct_def) => {
2191                 trans_struct_def(ccx, struct_def);
2192             }
2193         }
2194     }
2195 }
2196
2197 pub struct TransItemVisitor;
2198
2199 impl Visitor<@mut CrateContext> for TransItemVisitor {
2200     fn visit_item(&mut self, i: @ast::item, ccx: @mut CrateContext) {
2201         trans_item(ccx, i);
2202     }
2203 }
2204
2205 pub fn trans_item(ccx: @mut CrateContext, item: &ast::item) {
2206     let _icx = push_ctxt("trans_item");
2207     let path = match ccx.tcx.items.get_copy(&item.id) {
2208         ast_map::node_item(_, p) => p,
2209         // tjc: ?
2210         _ => fail!("trans_item"),
2211     };
2212     match item.node {
2213       ast::item_fn(ref decl, purity, _abis, ref generics, ref body) => {
2214         if purity == ast::extern_fn  {
2215             let llfndecl = get_item_val(ccx, item.id);
2216             foreign::trans_rust_fn_with_foreign_abi(
2217                 ccx,
2218                 &vec::append((*path).clone(),
2219                              [path_name(item.ident)]),
2220                 decl,
2221                 body,
2222                 llfndecl,
2223                 item.id);
2224         } else if !generics.is_type_parameterized() {
2225             let llfndecl = get_item_val(ccx, item.id);
2226             trans_fn(ccx,
2227                      vec::append((*path).clone(), [path_name(item.ident)]),
2228                      decl,
2229                      body,
2230                      llfndecl,
2231                      no_self,
2232                      None,
2233                      item.id,
2234                      item.attrs);
2235         } else {
2236             // Be sure to travel more than just one layer deep to catch nested
2237             // items in blocks and such.
2238             let mut v = TransItemVisitor;
2239             v.visit_block(body, ccx);
2240         }
2241       }
2242       ast::item_impl(ref generics, _, _, ref ms) => {
2243         meth::trans_impl(ccx,
2244                          (*path).clone(),
2245                          item.ident,
2246                          *ms,
2247                          generics,
2248                          item.id);
2249       }
2250       ast::item_mod(ref m) => {
2251         trans_mod(ccx, m);
2252       }
2253       ast::item_enum(ref enum_definition, ref generics) => {
2254         if !generics.is_type_parameterized() {
2255             let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
2256             let mut i = 0;
2257             trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
2258         }
2259       }
2260       ast::item_static(_, m, expr) => {
2261           consts::trans_const(ccx, m, item.id);
2262           // Do static_assert checking. It can't really be done much earlier
2263           // because we need to get the value of the bool out of LLVM
2264           if attr::contains_name(item.attrs, "static_assert") {
2265               if m == ast::MutMutable {
2266                   ccx.sess.span_fatal(expr.span,
2267                                       "cannot have static_assert on a mutable \
2268                                        static");
2269               }
2270               let v = ccx.const_values.get_copy(&item.id);
2271               unsafe {
2272                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
2273                       ccx.sess.span_fatal(expr.span, "static assertion failed");
2274                   }
2275               }
2276           }
2277       },
2278       ast::item_foreign_mod(ref foreign_mod) => {
2279         foreign::trans_foreign_mod(ccx, foreign_mod);
2280       }
2281       ast::item_struct(struct_def, ref generics) => {
2282         if !generics.is_type_parameterized() {
2283             trans_struct_def(ccx, struct_def);
2284         }
2285       }
2286       ast::item_trait(*) => {
2287         // Inside of this trait definition, we won't be actually translating any
2288         // functions, but the trait still needs to be walked. Otherwise default
2289         // methods with items will not get translated and will cause ICE's when
2290         // metadata time comes around.
2291         let mut v = TransItemVisitor;
2292         visit::walk_item(&mut v, item, ccx);
2293       }
2294       _ => {/* fall through */ }
2295     }
2296 }
2297
2298 pub fn trans_struct_def(ccx: @mut CrateContext, struct_def: @ast::struct_def) {
2299     // If this is a tuple-like struct, translate the constructor.
2300     match struct_def.ctor_id {
2301         // We only need to translate a constructor if there are fields;
2302         // otherwise this is a unit-like struct.
2303         Some(ctor_id) if struct_def.fields.len() > 0 => {
2304             let llfndecl = get_item_val(ccx, ctor_id);
2305             trans_tuple_struct(ccx, struct_def.fields,
2306                                ctor_id, None, llfndecl);
2307         }
2308         Some(_) | None => {}
2309     }
2310 }
2311
2312 // Translate a module. Doing this amounts to translating the items in the
2313 // module; there ends up being no artifact (aside from linkage names) of
2314 // separate modules in the compiled program.  That's because modules exist
2315 // only as a convenience for humans working with the code, to organize names
2316 // and control visibility.
2317 pub fn trans_mod(ccx: @mut CrateContext, m: &ast::_mod) {
2318     let _icx = push_ctxt("trans_mod");
2319     for item in m.items.iter() {
2320         trans_item(ccx, *item);
2321     }
2322 }
2323
2324 pub fn register_fn(ccx: @mut CrateContext,
2325                    sp: Span,
2326                    sym: ~str,
2327                    node_id: ast::NodeId,
2328                    node_type: ty::t)
2329                    -> ValueRef {
2330     let f = match ty::get(node_type).sty {
2331         ty::ty_bare_fn(ref f) => {
2332             assert!(f.abis.is_rust() || f.abis.is_intrinsic());
2333             f
2334         }
2335         _ => fail!("expected bare rust fn or an intrinsic")
2336     };
2337
2338     let llfn = decl_rust_fn(ccx, f.sig.inputs, f.sig.output, sym);
2339     ccx.item_symbols.insert(node_id, sym);
2340
2341     // FIXME #4404 android JNI hacks
2342     let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2343                       (*ccx.sess.building_library &&
2344                        ccx.sess.targ_cfg.os == session::OsAndroid));
2345     if is_entry {
2346         create_entry_wrapper(ccx, sp, llfn);
2347     }
2348     llfn
2349 }
2350
2351 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
2352 pub fn register_fn_llvmty(ccx: @mut CrateContext,
2353                           sp: Span,
2354                           sym: ~str,
2355                           node_id: ast::NodeId,
2356                           cc: lib::llvm::CallConv,
2357                           fn_ty: Type)
2358                           -> ValueRef {
2359     debug!("register_fn_fuller creating fn for item %d with path %s",
2360            node_id,
2361            ast_map::path_to_str(item_path(ccx, &node_id), token::get_ident_interner()));
2362
2363     let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty);
2364     ccx.item_symbols.insert(node_id, sym);
2365
2366     // FIXME #4404 android JNI hacks
2367     let is_entry = is_entry_fn(&ccx.sess, node_id) && (!*ccx.sess.building_library ||
2368                       (*ccx.sess.building_library &&
2369                        ccx.sess.targ_cfg.os == session::OsAndroid));
2370     if is_entry {
2371         create_entry_wrapper(ccx, sp, llfn);
2372     }
2373     llfn
2374 }
2375
2376 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
2377     match *sess.entry_fn {
2378         Some((entry_id, _)) => node_id == entry_id,
2379         None => false
2380     }
2381 }
2382
2383 // Create a _rust_main(args: ~[str]) function which will be called from the
2384 // runtime rust_start function
2385 pub fn create_entry_wrapper(ccx: @mut CrateContext,
2386                            _sp: Span,
2387                            main_llfn: ValueRef) {
2388     let et = ccx.sess.entry_type.unwrap();
2389     match et {
2390         session::EntryMain => {
2391             let llfn = create_main(ccx, main_llfn);
2392             create_entry_fn(ccx, llfn, true);
2393         }
2394         session::EntryStart => create_entry_fn(ccx, main_llfn, false),
2395         session::EntryNone => {}    // Do nothing.
2396     }
2397
2398     fn create_main(ccx: @mut CrateContext, main_llfn: ValueRef) -> ValueRef {
2399         let nt = ty::mk_nil();
2400         let llfty = type_of_rust_fn(ccx, [], nt);
2401         let llfdecl = decl_fn(ccx.llmod, "_rust_main",
2402                               lib::llvm::CCallConv, llfty);
2403
2404         let fcx = new_fn_ctxt(ccx, ~[], llfdecl, nt, None);
2405
2406         // the args vector built in create_entry_fn will need
2407         // be updated if this assertion starts to fail.
2408         assert!(!fcx.caller_expects_out_pointer);
2409
2410         let bcx = fcx.entry_bcx.unwrap();
2411         // Call main.
2412         let llenvarg = unsafe {
2413             let env_arg = fcx.env_arg_pos();
2414             llvm::LLVMGetParam(llfdecl, env_arg as c_uint)
2415         };
2416         let args = ~[llenvarg];
2417         Call(bcx, main_llfn, args, []);
2418
2419         finish_fn(fcx, bcx);
2420         return llfdecl;
2421     }
2422
2423     fn create_entry_fn(ccx: @mut CrateContext,
2424                        rust_main: ValueRef,
2425                        use_start_lang_item: bool) {
2426         let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
2427                                &ccx.int_type);
2428
2429         // FIXME #4404 android JNI hacks
2430         let main_name = if *ccx.sess.building_library {
2431             "amain"
2432         } else {
2433             "main"
2434         };
2435         let llfn = decl_cdecl_fn(ccx.llmod, main_name, llfty);
2436         let llbb = do "top".with_c_str |buf| {
2437             unsafe {
2438                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
2439             }
2440         };
2441         let bld = ccx.builder.B;
2442         unsafe {
2443             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
2444
2445             let crate_map = ccx.crate_map;
2446             let opaque_crate_map = do "crate_map".with_c_str |buf| {
2447                 llvm::LLVMBuildPointerCast(bld, crate_map, Type::i8p().to_ref(), buf)
2448             };
2449
2450             let (start_fn, args) = if use_start_lang_item {
2451                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
2452                     Ok(id) => id,
2453                     Err(s) => { ccx.tcx.sess.fatal(s); }
2454                 };
2455                 let start_fn = if start_def_id.crate == ast::LOCAL_CRATE {
2456                     get_item_val(ccx, start_def_id.node)
2457                 } else {
2458                     let start_fn_type = csearch::get_type(ccx.tcx,
2459                                                           start_def_id).ty;
2460                     trans_external_path(ccx, start_def_id, start_fn_type)
2461                 };
2462
2463                 let args = {
2464                     let opaque_rust_main = do "rust_main".with_c_str |buf| {
2465                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
2466                     };
2467
2468                     ~[
2469                         C_null(Type::opaque_box(ccx).ptr_to()),
2470                         opaque_rust_main,
2471                         llvm::LLVMGetParam(llfn, 0),
2472                         llvm::LLVMGetParam(llfn, 1),
2473                         opaque_crate_map
2474                      ]
2475                 };
2476                 (start_fn, args)
2477             } else {
2478                 debug!("using user-defined start fn");
2479                 let args = ~[
2480                     C_null(Type::opaque_box(ccx).ptr_to()),
2481                     llvm::LLVMGetParam(llfn, 0 as c_uint),
2482                     llvm::LLVMGetParam(llfn, 1 as c_uint),
2483                     opaque_crate_map
2484                 ];
2485
2486                 (rust_main, args)
2487             };
2488
2489             let result = do args.as_imm_buf |buf, len| {
2490                 llvm::LLVMBuildCall(bld, start_fn, buf, len as c_uint, noname())
2491             };
2492
2493             llvm::LLVMBuildRet(bld, result);
2494         }
2495     }
2496 }
2497
2498 pub fn fill_fn_pair(bcx: @mut Block, pair: ValueRef, llfn: ValueRef,
2499                     llenvptr: ValueRef) {
2500     let ccx = bcx.ccx();
2501     let code_cell = GEPi(bcx, pair, [0u, abi::fn_field_code]);
2502     Store(bcx, llfn, code_cell);
2503     let env_cell = GEPi(bcx, pair, [0u, abi::fn_field_box]);
2504     let llenvblobptr = PointerCast(bcx, llenvptr, Type::opaque_box(ccx).ptr_to());
2505     Store(bcx, llenvblobptr, env_cell);
2506 }
2507
2508 pub fn item_path(ccx: &CrateContext, id: &ast::NodeId) -> path {
2509     ty::item_path(ccx.tcx, ast_util::local_def(*id))
2510 }
2511
2512 fn exported_name(ccx: @mut CrateContext, path: path, ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
2513     match attr::first_attr_value_str_by_name(attrs, "export_name") {
2514         // Use provided name
2515         Some(name) => name.to_owned(),
2516
2517         // Don't mangle
2518         _ if attr::contains_name(attrs, "no_mangle")
2519             => path_elt_to_str(*path.last(), token::get_ident_interner()),
2520
2521         // Usual name mangling
2522         _ => mangle_exported_name(ccx, path, ty)
2523     }
2524 }
2525
2526 pub fn get_item_val(ccx: @mut CrateContext, id: ast::NodeId) -> ValueRef {
2527     debug!("get_item_val(id=`%?`)", id);
2528
2529     let val = ccx.item_vals.find_copy(&id);
2530     match val {
2531         Some(v) => v,
2532         None => {
2533             let mut exprt = false;
2534             let item = ccx.tcx.items.get_copy(&id);
2535             let val = match item {
2536                 ast_map::node_item(i, pth) => {
2537
2538                     let elt = path_pretty_name(i.ident, id as u64);
2539                     let my_path = vec::append_one((*pth).clone(), elt);
2540                     let ty = ty::node_id_to_type(ccx.tcx, i.id);
2541                     let sym = exported_name(ccx, my_path, ty, i.attrs);
2542
2543                     let v = match i.node {
2544                         ast::item_static(_, _, expr) => {
2545                             // If this static came from an external crate, then
2546                             // we need to get the symbol from csearch instead of
2547                             // using the current crate's name/version
2548                             // information in the hash of the symbol
2549                             debug!("making %s", sym);
2550                             let sym = match ccx.external_srcs.find(&i.id) {
2551                                 Some(&did) => {
2552                                     debug!("but found in other crate...");
2553                                     csearch::get_symbol(ccx.sess.cstore, did)
2554                                 }
2555                                 None => sym
2556                             };
2557
2558                             // We need the translated value here, because for enums the
2559                             // LLVM type is not fully determined by the Rust type.
2560                             let (v, inlineable) = consts::const_expr(ccx, expr);
2561                             ccx.const_values.insert(id, v);
2562                             if !inlineable {
2563                                 debug!("%s not inlined", sym);
2564                                 ccx.non_inlineable_statics.insert(id);
2565                             }
2566                             exprt = true;
2567
2568                             unsafe {
2569                                 let llty = llvm::LLVMTypeOf(v);
2570                                 let g = do sym.with_c_str |buf| {
2571                                     llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
2572                                 };
2573
2574                                 // Apply the `unnamed_addr` attribute if
2575                                 // requested
2576                                 if attr::contains_name(i.attrs,
2577                                                        "address_insignificant"){
2578                                     lib::llvm::SetUnnamedAddr(g, true);
2579                                     lib::llvm::SetLinkage(g,
2580                                         lib::llvm::InternalLinkage);
2581                                 }
2582
2583                                 ccx.item_symbols.insert(i.id, sym);
2584                                 g
2585                             }
2586                         }
2587
2588                         ast::item_fn(_, purity, _, _, _) => {
2589                             let llfn = if purity != ast::extern_fn {
2590                                 register_fn(ccx, i.span, sym, i.id, ty)
2591                             } else {
2592                                 foreign::register_rust_fn_with_foreign_abi(ccx,
2593                                                                            i.span,
2594                                                                            sym,
2595                                                                            i.id)
2596                             };
2597                             set_llvm_fn_attrs(i.attrs, llfn);
2598                             llfn
2599                         }
2600
2601                         _ => fail!("get_item_val: weird result in table")
2602                     };
2603
2604                     match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
2605                         Some(sect) => unsafe {
2606                             do sect.with_c_str |buf| {
2607                                 llvm::LLVMSetSection(v, buf);
2608                             }
2609                         },
2610                         None => ()
2611                     }
2612
2613                     v
2614                 }
2615
2616                 ast_map::node_trait_method(trait_method, _, pth) => {
2617                     debug!("get_item_val(): processing a node_trait_method");
2618                     match *trait_method {
2619                         ast::required(_) => {
2620                             ccx.sess.bug("unexpected variant: required trait method in \
2621                                          get_item_val()");
2622                         }
2623                         ast::provided(m) => {
2624                             exprt = true;
2625                             register_method(ccx, id, pth, m)
2626                         }
2627                     }
2628                 }
2629
2630                 ast_map::node_method(m, _, pth) => {
2631                     register_method(ccx, id, pth, m)
2632                 }
2633
2634                 ast_map::node_foreign_item(ni, abis, _, pth) => {
2635                     let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2636                     exprt = true;
2637
2638                     match ni.node {
2639                         ast::foreign_item_fn(*) => {
2640                             let path = vec::append((*pth).clone(), [path_name(ni.ident)]);
2641                             foreign::register_foreign_item_fn(ccx, abis, &path, ni)
2642                         }
2643                         ast::foreign_item_static(*) => {
2644                             let ident = token::ident_to_str(&ni.ident);
2645                             let g = do ident.with_c_str |buf| {
2646                                 unsafe {
2647                                     let ty = type_of(ccx, ty);
2648                                     llvm::LLVMAddGlobal(ccx.llmod, ty.to_ref(), buf)
2649                                 }
2650                             };
2651                             g
2652                         }
2653                     }
2654                 }
2655
2656                 ast_map::node_variant(ref v, enm, pth) => {
2657                     let llfn;
2658                     match v.node.kind {
2659                         ast::tuple_variant_kind(ref args) => {
2660                             assert!(args.len() != 0u);
2661                             let pth = vec::append((*pth).clone(),
2662                                                   [path_name(enm.ident),
2663                                                    path_name((*v).node.name)]);
2664                             let ty = ty::node_id_to_type(ccx.tcx, id);
2665                             let sym = exported_name(ccx, pth, ty, enm.attrs);
2666
2667                             llfn = match enm.node {
2668                                 ast::item_enum(_, _) => {
2669                                     register_fn(ccx, (*v).span, sym, id, ty)
2670                                 }
2671                                 _ => fail!("node_variant, shouldn't happen")
2672                             };
2673                         }
2674                         ast::struct_variant_kind(_) => {
2675                             fail!("struct variant kind unexpected in get_item_val")
2676                         }
2677                     }
2678                     set_inline_hint(llfn);
2679                     llfn
2680                 }
2681
2682                 ast_map::node_struct_ctor(struct_def, struct_item, struct_path) => {
2683                     // Only register the constructor if this is a tuple-like struct.
2684                     match struct_def.ctor_id {
2685                         None => {
2686                             ccx.tcx.sess.bug("attempt to register a constructor of \
2687                                               a non-tuple-like struct")
2688                         }
2689                         Some(ctor_id) => {
2690                             let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2691                             let sym = exported_name(ccx, (*struct_path).clone(), ty,
2692                                                     struct_item.attrs);
2693                             let llfn = register_fn(ccx, struct_item.span,
2694                                                    sym, ctor_id, ty);
2695                             set_inline_hint(llfn);
2696                             llfn
2697                         }
2698                     }
2699                 }
2700
2701                 ref variant => {
2702                     ccx.sess.bug(fmt!("get_item_val(): unexpected variant: %?",
2703                                  variant))
2704                 }
2705             };
2706
2707             if !exprt && !ccx.reachable.contains(&id) {
2708                 lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2709             }
2710
2711             ccx.item_vals.insert(id, val);
2712             val
2713         }
2714     }
2715 }
2716
2717 pub fn register_method(ccx: @mut CrateContext,
2718                        id: ast::NodeId,
2719                        path: @ast_map::path,
2720                        m: @ast::method) -> ValueRef {
2721     let mty = ty::node_id_to_type(ccx.tcx, id);
2722
2723     let mut path = (*path).clone();
2724     path.push(path_pretty_name(m.ident, token::gensym("meth") as u64));
2725
2726     let sym = exported_name(ccx, path, mty, m.attrs);
2727
2728     let llfn = register_fn(ccx, m.span, sym, id, mty);
2729     set_llvm_fn_attrs(m.attrs, llfn);
2730     llfn
2731 }
2732
2733 pub fn vp2i(cx: @mut Block, v: ValueRef) -> ValueRef {
2734     let ccx = cx.ccx();
2735     return PtrToInt(cx, v, ccx.int_type);
2736 }
2737
2738 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2739     unsafe {
2740         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2741     }
2742 }
2743
2744 macro_rules! ifn (
2745     ($intrinsics:ident, $name:expr, $args:expr, $ret:expr) => ({
2746         let name = $name;
2747         let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret));
2748         $intrinsics.insert(name, f);
2749     })
2750 )
2751
2752 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2753     let i8p = Type::i8p();
2754     let mut intrinsics = HashMap::new();
2755
2756     ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i32",
2757          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2758     ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i64",
2759          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2760     ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i32",
2761          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2762     ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i64",
2763          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2764     ifn!(intrinsics, "llvm.memset.p0i8.i32",
2765          [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2766     ifn!(intrinsics, "llvm.memset.p0i8.i64",
2767          [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2768
2769     ifn!(intrinsics, "llvm.trap", [], Type::void());
2770     ifn!(intrinsics, "llvm.frameaddress", [Type::i32()], i8p);
2771
2772     ifn!(intrinsics, "llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2773     ifn!(intrinsics, "llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2774     ifn!(intrinsics, "llvm.pow.f32",  [Type::f32(), Type::f32()], Type::f32());
2775     ifn!(intrinsics, "llvm.pow.f64",  [Type::f64(), Type::f64()], Type::f64());
2776
2777     ifn!(intrinsics, "llvm.sqrt.f32", [Type::f32()], Type::f32());
2778     ifn!(intrinsics, "llvm.sqrt.f64", [Type::f64()], Type::f64());
2779     ifn!(intrinsics, "llvm.sin.f32",  [Type::f32()], Type::f32());
2780     ifn!(intrinsics, "llvm.sin.f64",  [Type::f64()], Type::f64());
2781     ifn!(intrinsics, "llvm.cos.f32",  [Type::f32()], Type::f32());
2782     ifn!(intrinsics, "llvm.cos.f64",  [Type::f64()], Type::f64());
2783     ifn!(intrinsics, "llvm.exp.f32",  [Type::f32()], Type::f32());
2784     ifn!(intrinsics, "llvm.exp.f64",  [Type::f64()], Type::f64());
2785     ifn!(intrinsics, "llvm.exp2.f32", [Type::f32()], Type::f32());
2786     ifn!(intrinsics, "llvm.exp2.f64", [Type::f64()], Type::f64());
2787     ifn!(intrinsics, "llvm.log.f32",  [Type::f32()], Type::f32());
2788     ifn!(intrinsics, "llvm.log.f64",  [Type::f64()], Type::f64());
2789     ifn!(intrinsics, "llvm.log10.f32",[Type::f32()], Type::f32());
2790     ifn!(intrinsics, "llvm.log10.f64",[Type::f64()], Type::f64());
2791     ifn!(intrinsics, "llvm.log2.f32", [Type::f32()], Type::f32());
2792     ifn!(intrinsics, "llvm.log2.f64", [Type::f64()], Type::f64());
2793
2794     ifn!(intrinsics, "llvm.fma.f32",  [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2795     ifn!(intrinsics, "llvm.fma.f64",  [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2796
2797     ifn!(intrinsics, "llvm.fabs.f32", [Type::f32()], Type::f32());
2798     ifn!(intrinsics, "llvm.fabs.f64", [Type::f64()], Type::f64());
2799     ifn!(intrinsics, "llvm.floor.f32",[Type::f32()], Type::f32());
2800     ifn!(intrinsics, "llvm.floor.f64",[Type::f64()], Type::f64());
2801     ifn!(intrinsics, "llvm.ceil.f32", [Type::f32()], Type::f32());
2802     ifn!(intrinsics, "llvm.ceil.f64", [Type::f64()], Type::f64());
2803     ifn!(intrinsics, "llvm.trunc.f32",[Type::f32()], Type::f32());
2804     ifn!(intrinsics, "llvm.trunc.f64",[Type::f64()], Type::f64());
2805
2806     ifn!(intrinsics, "llvm.ctpop.i8", [Type::i8()], Type::i8());
2807     ifn!(intrinsics, "llvm.ctpop.i16",[Type::i16()], Type::i16());
2808     ifn!(intrinsics, "llvm.ctpop.i32",[Type::i32()], Type::i32());
2809     ifn!(intrinsics, "llvm.ctpop.i64",[Type::i64()], Type::i64());
2810
2811     ifn!(intrinsics, "llvm.ctlz.i8",  [Type::i8() , Type::i1()], Type::i8());
2812     ifn!(intrinsics, "llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2813     ifn!(intrinsics, "llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2814     ifn!(intrinsics, "llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2815
2816     ifn!(intrinsics, "llvm.cttz.i8",  [Type::i8() , Type::i1()], Type::i8());
2817     ifn!(intrinsics, "llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2818     ifn!(intrinsics, "llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2819     ifn!(intrinsics, "llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2820
2821     ifn!(intrinsics, "llvm.bswap.i16",[Type::i16()], Type::i16());
2822     ifn!(intrinsics, "llvm.bswap.i32",[Type::i32()], Type::i32());
2823     ifn!(intrinsics, "llvm.bswap.i64",[Type::i64()], Type::i64());
2824
2825     ifn!(intrinsics, "llvm.sadd.with.overflow.i8",
2826         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2827     ifn!(intrinsics, "llvm.sadd.with.overflow.i16",
2828         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2829     ifn!(intrinsics, "llvm.sadd.with.overflow.i32",
2830         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2831     ifn!(intrinsics, "llvm.sadd.with.overflow.i64",
2832         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2833
2834     ifn!(intrinsics, "llvm.uadd.with.overflow.i8",
2835         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2836     ifn!(intrinsics, "llvm.uadd.with.overflow.i16",
2837         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2838     ifn!(intrinsics, "llvm.uadd.with.overflow.i32",
2839         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2840     ifn!(intrinsics, "llvm.uadd.with.overflow.i64",
2841         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2842
2843     ifn!(intrinsics, "llvm.ssub.with.overflow.i8",
2844         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2845     ifn!(intrinsics, "llvm.ssub.with.overflow.i16",
2846         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2847     ifn!(intrinsics, "llvm.ssub.with.overflow.i32",
2848         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2849     ifn!(intrinsics, "llvm.ssub.with.overflow.i64",
2850         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2851
2852     ifn!(intrinsics, "llvm.usub.with.overflow.i8",
2853         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2854     ifn!(intrinsics, "llvm.usub.with.overflow.i16",
2855         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2856     ifn!(intrinsics, "llvm.usub.with.overflow.i32",
2857         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2858     ifn!(intrinsics, "llvm.usub.with.overflow.i64",
2859         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2860
2861     ifn!(intrinsics, "llvm.smul.with.overflow.i8",
2862         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2863     ifn!(intrinsics, "llvm.smul.with.overflow.i16",
2864         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2865     ifn!(intrinsics, "llvm.smul.with.overflow.i32",
2866         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2867     ifn!(intrinsics, "llvm.smul.with.overflow.i64",
2868         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2869
2870     ifn!(intrinsics, "llvm.umul.with.overflow.i8",
2871         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2872     ifn!(intrinsics, "llvm.umul.with.overflow.i16",
2873         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2874     ifn!(intrinsics, "llvm.umul.with.overflow.i32",
2875         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2876     ifn!(intrinsics, "llvm.umul.with.overflow.i64",
2877         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2878
2879     return intrinsics;
2880 }
2881
2882 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2883     ifn!(intrinsics, "llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2884     ifn!(intrinsics,
2885          "llvm.dbg.value",   [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2886 }
2887
2888 pub fn trap(bcx: @mut Block) {
2889     match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2890       Some(&x) => { Call(bcx, x, [], []); },
2891       _ => bcx.sess().bug("unbound llvm.trap in trap")
2892     }
2893 }
2894
2895 pub fn decl_gc_metadata(ccx: &mut CrateContext, llmod_id: &str) {
2896     if !ccx.sess.opts.gc || !ccx.uses_gc {
2897         return;
2898     }
2899
2900     let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2901     let gc_metadata = do gc_metadata_name.with_c_str |buf| {
2902         unsafe {
2903             llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2904         }
2905     };
2906     unsafe {
2907         llvm::LLVMSetGlobalConstant(gc_metadata, True);
2908         lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2909         ccx.module_data.insert(~"_gc_module_metadata", gc_metadata);
2910     }
2911 }
2912
2913 pub fn create_module_map(ccx: &mut CrateContext) -> ValueRef {
2914     let elttype = Type::struct_([ccx.int_type, ccx.int_type], false);
2915     let maptype = Type::array(&elttype, (ccx.module_data.len() + 1) as u64);
2916     let map = do "_rust_mod_map".with_c_str |buf| {
2917         unsafe {
2918             llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2919         }
2920     };
2921     lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2922     let mut elts: ~[ValueRef] = ~[];
2923
2924     // This is not ideal, but the borrow checker doesn't
2925     // like the multiple borrows. At least, it doesn't
2926     // like them on the current snapshot. (2013-06-14)
2927     let mut keys = ~[];
2928     for (k, _) in ccx.module_data.iter() {
2929         keys.push(k.to_managed());
2930     }
2931
2932     for key in keys.iter() {
2933         let val = *ccx.module_data.find_equiv(key).unwrap();
2934         let s_const = C_cstr(ccx, *key);
2935         let s_ptr = p2i(ccx, s_const);
2936         let v_ptr = p2i(ccx, val);
2937         let elt = C_struct([s_ptr, v_ptr]);
2938         elts.push(elt);
2939     }
2940     let term = C_struct([C_int(ccx, 0), C_int(ccx, 0)]);
2941     elts.push(term);
2942     unsafe {
2943         llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2944     }
2945     return map;
2946 }
2947
2948
2949 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2950                       llmod: ModuleRef) -> ValueRef {
2951     let targ_cfg = sess.targ_cfg;
2952     let int_type = Type::int(targ_cfg.arch);
2953     let mut n_subcrates = 1;
2954     let cstore = sess.cstore;
2955     while cstore::have_crate_data(cstore, n_subcrates) { n_subcrates += 1; }
2956     let mapname = if *sess.building_library {
2957         fmt!("%s_%s_%s", mapmeta.name, mapmeta.vers, mapmeta.extras_hash)
2958     } else {
2959         ~"toplevel"
2960     };
2961     let sym_name = ~"_rust_crate_map_" + mapname;
2962     let arrtype = Type::array(&int_type, n_subcrates as u64);
2963     let maptype = Type::struct_([Type::i32(), Type::i8p(), int_type, arrtype], false);
2964     let map = do sym_name.with_c_str |buf| {
2965         unsafe {
2966             llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2967         }
2968     };
2969     lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2970     return map;
2971 }
2972
2973 pub fn fill_crate_map(ccx: @mut CrateContext, map: ValueRef) {
2974     let mut subcrates: ~[ValueRef] = ~[];
2975     let mut i = 1;
2976     let cstore = ccx.sess.cstore;
2977     while cstore::have_crate_data(cstore, i) {
2978         let cdata = cstore::get_crate_data(cstore, i);
2979         let nm = fmt!("_rust_crate_map_%s_%s_%s",
2980                       cdata.name,
2981                       cstore::get_crate_vers(cstore, i),
2982                       cstore::get_crate_hash(cstore, i));
2983         let cr = do nm.with_c_str |buf| {
2984             unsafe {
2985                 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2986             }
2987         };
2988         subcrates.push(p2i(ccx, cr));
2989         i += 1;
2990     }
2991     subcrates.push(C_int(ccx, 0));
2992
2993     unsafe {
2994         let mod_map = create_module_map(ccx);
2995         llvm::LLVMSetInitializer(map, C_struct(
2996             [C_i32(1),
2997              // FIXME #8431 This used to be the annihilate function, now it's nothing
2998              C_null(Type::i8p()),
2999              p2i(ccx, mod_map),
3000              C_array(ccx.int_type, subcrates)]));
3001     }
3002 }
3003
3004 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::encode_inlined_item<'r>)
3005     -> encoder::EncodeParams<'r> {
3006
3007         let diag = cx.sess.diagnostic();
3008         let item_symbols = &cx.item_symbols;
3009         let discrim_symbols = &cx.discrim_symbols;
3010         let link_meta = &cx.link_meta;
3011         encoder::EncodeParams {
3012             diag: diag,
3013             tcx: cx.tcx,
3014             reexports2: cx.exp_map2,
3015             item_symbols: item_symbols,
3016             discrim_symbols: discrim_symbols,
3017             non_inlineable_statics: &cx.non_inlineable_statics,
3018             link_meta: link_meta,
3019             cstore: cx.sess.cstore,
3020             encode_inlined_item: ie,
3021             reachable: cx.reachable,
3022         }
3023 }
3024
3025 pub fn write_metadata(cx: &mut CrateContext, crate: &ast::Crate) {
3026     if !*cx.sess.building_library { return; }
3027
3028     let encode_inlined_item: encoder::encode_inlined_item =
3029         |ecx, ebml_w, path, ii|
3030         astencode::encode_inlined_item(ecx, ebml_w, path, ii, cx.maps);
3031
3032     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
3033     let llmeta = C_bytes(encoder::encode_metadata(encode_parms, crate));
3034     let llconst = C_struct([llmeta]);
3035     let mut llglobal = do "rust_metadata".with_c_str |buf| {
3036         unsafe {
3037             llvm::LLVMAddGlobal(cx.llmod, val_ty(llconst).to_ref(), buf)
3038         }
3039     };
3040     unsafe {
3041         llvm::LLVMSetInitializer(llglobal, llconst);
3042         do cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str |buf| {
3043             llvm::LLVMSetSection(llglobal, buf)
3044         };
3045         lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
3046
3047         let t_ptr_i8 = Type::i8p();
3048         llglobal = llvm::LLVMConstBitCast(llglobal, t_ptr_i8.to_ref());
3049         let llvm_used = do "llvm.used".with_c_str |buf| {
3050             llvm::LLVMAddGlobal(cx.llmod, Type::array(&t_ptr_i8, 1).to_ref(), buf)
3051         };
3052         lib::llvm::SetLinkage(llvm_used, lib::llvm::AppendingLinkage);
3053         llvm::LLVMSetInitializer(llvm_used, C_array(t_ptr_i8, [llglobal]));
3054     }
3055 }
3056
3057 fn mk_global(ccx: &CrateContext,
3058              name: &str,
3059              llval: ValueRef,
3060              internal: bool)
3061           -> ValueRef {
3062     unsafe {
3063         let llglobal = do name.with_c_str |buf| {
3064             llvm::LLVMAddGlobal(ccx.llmod, val_ty(llval).to_ref(), buf)
3065         };
3066         llvm::LLVMSetInitializer(llglobal, llval);
3067         llvm::LLVMSetGlobalConstant(llglobal, True);
3068
3069         if internal {
3070             lib::llvm::SetLinkage(llglobal, lib::llvm::InternalLinkage);
3071         }
3072
3073         return llglobal;
3074     }
3075 }
3076
3077 // Writes the current ABI version into the crate.
3078 pub fn write_abi_version(ccx: &mut CrateContext) {
3079     mk_global(ccx, "rust_abi_version", C_uint(ccx, abi::abi_version), false);
3080 }
3081
3082 pub fn trans_crate(sess: session::Session,
3083                    crate: &ast::Crate,
3084                    analysis: &CrateAnalysis,
3085                    output: &Path) -> CrateTranslation {
3086     // Before we touch LLVM, make sure that multithreading is enabled.
3087     if unsafe { !llvm::LLVMRustStartMultithreading() } {
3088         //sess.bug("couldn't enable multi-threaded LLVM");
3089     }
3090
3091     let mut symbol_hasher = hash::default_state();
3092     let link_meta = link::build_link_meta(sess, crate, output, &mut symbol_hasher);
3093
3094     // Append ".rc" to crate name as LLVM module identifier.
3095     //
3096     // LLVM code generator emits a ".file filename" directive
3097     // for ELF backends. Value of the "filename" is set as the
3098     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
3099     // crashes if the module identifer is same as other symbols
3100     // such as a function name in the module.
3101     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
3102     let llmod_id = link_meta.name.to_owned() + ".rc";
3103
3104     let ccx = @mut CrateContext::new(sess,
3105                                      llmod_id,
3106                                      analysis.ty_cx,
3107                                      analysis.exp_map2,
3108                                      analysis.maps,
3109                                      symbol_hasher,
3110                                      link_meta,
3111                                      analysis.reachable);
3112
3113     if ccx.sess.opts.debuginfo {
3114         debuginfo::initialize(ccx, crate);
3115     }
3116
3117     {
3118         let _icx = push_ctxt("text");
3119         trans_mod(ccx, &crate.module);
3120     }
3121
3122     decl_gc_metadata(ccx, llmod_id);
3123     fill_crate_map(ccx, ccx.crate_map);
3124     glue::emit_tydescs(ccx);
3125     write_abi_version(ccx);
3126     if ccx.sess.opts.debuginfo {
3127         debuginfo::finalize(ccx);
3128     }
3129
3130     // Translate the metadata.
3131     write_metadata(ccx, crate);
3132     if ccx.sess.trans_stats() {
3133         io::println("--- trans stats ---");
3134         printfln!("n_static_tydescs: %u", ccx.stats.n_static_tydescs);
3135         printfln!("n_glues_created: %u", ccx.stats.n_glues_created);
3136         printfln!("n_null_glues: %u", ccx.stats.n_null_glues);
3137         printfln!("n_real_glues: %u", ccx.stats.n_real_glues);
3138
3139         printfln!("n_fns: %u", ccx.stats.n_fns);
3140         printfln!("n_monos: %u", ccx.stats.n_monos);
3141         printfln!("n_inlines: %u", ccx.stats.n_inlines);
3142         printfln!("n_closures: %u", ccx.stats.n_closures);
3143         io::println("fn stats:");
3144         do sort::quick_sort(ccx.stats.fn_stats) |&(_, _, insns_a), &(_, _, insns_b)| {
3145             insns_a > insns_b
3146         }
3147         for tuple in ccx.stats.fn_stats.iter() {
3148             match *tuple {
3149                 (ref name, ms, insns) => {
3150                     printfln!("%u insns, %u ms, %s", insns, ms, *name);
3151                 }
3152             }
3153         }
3154     }
3155     if ccx.sess.count_llvm_insns() {
3156         for (k, v) in ccx.stats.llvm_insns.iter() {
3157             printfln!("%-7u %s", *v, *k);
3158         }
3159     }
3160
3161     let llcx = ccx.llcx;
3162     let link_meta = ccx.link_meta;
3163     let llmod = ccx.llmod;
3164
3165     return CrateTranslation {
3166         context: llcx,
3167         module: llmod,
3168         link: link_meta
3169     };
3170 }