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