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