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