]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
625b130d47af96be708b871d3580dbbf4a6696fd
[rust.git] / src / librustc / middle / trans / base.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // trans.rs: Translate the completed AST to the LLVM IR.
12 //
13 // Some functions here, such as trans_block and trans_expr, return a value --
14 // the result of the translation to LLVM -- while others, such as trans_fn,
15 // trans_impl, and trans_item, are called only for the side effect of adding a
16 // particular definition to the LLVM IR output we're producing.
17 //
18 // Hopefully useful general knowledge about trans:
19 //
20 //   * There's no way to find out the ty::t type of a ValueRef.  Doing so
21 //     would be "trying to get the eggs out of an omelette" (credit:
22 //     pcwalton).  You can, instead, find out its TypeRef by calling val_ty,
23 //     but one TypeRef corresponds to many `ty::t`s; for instance, tup(int, int,
24 //     int) and rec(x=int, y=int, z=int) will have the same TypeRef.
25
26 #[allow(non_camel_case_types)];
27
28 use back::link::{mangle_exported_name};
29 use back::{link, abi};
30 use driver::session;
31 use driver::session::{Session, NoDebugInfo, FullDebugInfo};
32 use driver::driver::OutputFilenames;
33 use driver::driver::{CrateAnalysis, CrateTranslation};
34 use lib::llvm::{ModuleRef, ValueRef, BasicBlockRef};
35 use lib::llvm::{llvm, True, Vector};
36 use lib;
37 use metadata::common::LinkMeta;
38 use metadata::{csearch, encoder};
39 use middle::astencode;
40 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
41 use middle::lang_items::{MallocFnLangItem, ClosureExchangeMallocFnLangItem};
42 use middle::trans::_match;
43 use middle::trans::adt;
44 use middle::trans::build::*;
45 use middle::trans::builder::{Builder, noname};
46 use middle::trans::callee;
47 use middle::trans::cleanup;
48 use middle::trans::cleanup::CleanupMethods;
49 use middle::trans::common::*;
50 use middle::trans::consts;
51 use middle::trans::controlflow;
52 use middle::trans::datum;
53 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
54 use middle::trans::debuginfo;
55 use middle::trans::expr;
56 use middle::trans::foreign;
57 use middle::trans::glue;
58 use middle::trans::inline;
59 use middle::trans::machine;
60 use middle::trans::machine::{llalign_of_min, llsize_of};
61 use middle::trans::meth;
62 use middle::trans::monomorphize;
63 use middle::trans::tvec;
64 use middle::trans::type_::Type;
65 use middle::trans::type_of;
66 use middle::trans::type_of::*;
67 use middle::trans::value::Value;
68 use middle::ty;
69 use middle::typeck;
70 use util::common::indenter;
71 use util::ppaux::{Repr, ty_to_str};
72 use util::sha2::Sha256;
73 use util::nodemap::NodeMap;
74
75 use arena::TypedArena;
76 use std::c_str::ToCStr;
77 use std::cell::{Cell, RefCell};
78 use collections::HashMap;
79 use std::libc::c_uint;
80 use std::local_data;
81 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic, OsWin32};
82 use syntax::ast_map::PathName;
83 use syntax::ast_util::{local_def, is_local};
84 use syntax::attr::AttrMetaMethods;
85 use syntax::attr;
86 use syntax::codemap::Span;
87 use syntax::parse::token::InternedString;
88 use syntax::parse::token;
89 use syntax::visit::Visitor;
90 use syntax::visit;
91 use syntax::{ast, ast_util, ast_map};
92
93 use time;
94
95 pub use middle::trans::context::task_llcx;
96
97 local_data_key!(task_local_insn_key: ~[&'static str])
98
99 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
100     local_data::get(task_local_insn_key, |c| {
101         match c {
102             Some(ctx) => blk(*ctx),
103             None => ()
104         }
105     })
106 }
107
108 pub fn init_insn_ctxt() {
109     local_data::set(task_local_insn_key, ~[]);
110 }
111
112 pub struct _InsnCtxt { _x: () }
113
114 #[unsafe_destructor]
115 impl Drop for _InsnCtxt {
116     fn drop(&mut self) {
117         local_data::modify(task_local_insn_key, |c| {
118             c.map(|mut ctx| {
119                 ctx.pop();
120                 ctx
121             })
122         })
123     }
124 }
125
126 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
127     debug!("new InsnCtxt: {}", s);
128     local_data::modify(task_local_insn_key, |c| {
129         c.map(|mut ctx| {
130             ctx.push(s);
131             ctx
132         })
133     });
134     _InsnCtxt { _x: () }
135 }
136
137 pub struct StatRecorder {
138     ccx: @CrateContext,
139     name: Option<~str>,
140     start: u64,
141     istart: uint,
142 }
143
144 impl StatRecorder {
145     pub fn new(ccx: @CrateContext, name: ~str) -> StatRecorder {
146         let start = if ccx.sess.trans_stats() {
147             time::precise_time_ns()
148         } else {
149             0
150         };
151         let istart = ccx.stats.n_llvm_insns.get();
152         StatRecorder {
153             ccx: ccx,
154             name: Some(name),
155             start: start,
156             istart: istart,
157         }
158     }
159 }
160
161 #[unsafe_destructor]
162 impl Drop for StatRecorder {
163     fn drop(&mut self) {
164         if self.ccx.sess.trans_stats() {
165             let end = time::precise_time_ns();
166             let elapsed = ((end - self.start) / 1_000_000) as uint;
167             let iend = self.ccx.stats.n_llvm_insns.get();
168             {
169                 let mut fn_stats = self.ccx.stats.fn_stats.borrow_mut();
170                 fn_stats.get().push((self.name.take_unwrap(),
171                                      elapsed,
172                                      iend - self.istart));
173             }
174             self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
175             // Reset LLVM insn count to avoid compound costs.
176             self.ccx.stats.n_llvm_insns.set(self.istart);
177         }
178     }
179 }
180
181 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
182 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
183            ty: Type, output: ty::t) -> ValueRef {
184     let llfn: ValueRef = name.with_c_str(|buf| {
185         unsafe {
186             llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
187         }
188     });
189
190     match ty::get(output).sty {
191         // functions returning bottom may unwind, but can never return normally
192         ty::ty_bot => {
193             unsafe {
194                 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
195             }
196         }
197         // `~` pointer return values never alias because ownership is transferred
198         // FIXME #6750 ~Trait cannot be directly marked as
199         // noalias because the actual object pointer is nested.
200         ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
201         ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) => {
202             unsafe {
203                 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
204             }
205         }
206         _ => {}
207     }
208
209     lib::llvm::SetFunctionCallConv(llfn, cc);
210     // Function addresses in Rust are never significant, allowing functions to be merged.
211     lib::llvm::SetUnnamedAddr(llfn, true);
212
213     llfn
214 }
215
216 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
217 pub fn decl_cdecl_fn(llmod: ModuleRef,
218                      name: &str,
219                      ty: Type,
220                      output: ty::t) -> ValueRef {
221     decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
222 }
223
224 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
225 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
226                      name: &str, cc: lib::llvm::CallConv,
227                      ty: Type, output: ty::t) -> ValueRef {
228     match externs.find_equiv(&name) {
229         Some(n) => return *n,
230         None => {}
231     }
232     let f = decl_fn(llmod, name, cc, ty, output);
233     externs.insert(name.to_owned(), f);
234     f
235 }
236
237 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
238                       name: &str, did: ast::DefId) -> ValueRef {
239     {
240         let externs = ccx.externs.borrow();
241         match externs.get().find_equiv(&name) {
242             Some(n) => return *n,
243             None => ()
244         }
245     }
246
247     let f = decl_rust_fn(ccx, false, inputs, output, name);
248     csearch::get_item_attrs(ccx.tcx.cstore, did, |meta_items| {
249         set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x)).to_owned_vec(), f)
250     });
251
252     let mut externs = ccx.externs.borrow_mut();
253     externs.get().insert(name.to_owned(), f);
254     f
255 }
256
257 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
258                     inputs: &[ty::t], output: ty::t,
259                     name: &str) -> ValueRef {
260     let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
261     let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
262
263     let uses_outptr = type_of::return_uses_outptr(ccx, output);
264     let offset = if uses_outptr { 1 } else { 0 };
265     let offset = if has_env { offset + 1 } else { offset };
266
267     for (i, &arg_ty) in inputs.iter().enumerate() {
268         let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
269         match ty::get(arg_ty).sty {
270             // `~` pointer parameters never alias because ownership is transferred
271             // FIXME #6750 ~Trait cannot be directly marked as
272             // noalias because the actual object pointer is nested.
273             ty::ty_uniq(..) | // ty::ty_trait(_, _, ty::UniqTraitStore, _, _) |
274             ty::ty_vec(_, ty::vstore_uniq) | ty::ty_str(ty::vstore_uniq) |
275             ty::ty_closure(ty::ClosureTy {sigil: ast::OwnedSigil, ..}) => {
276                 unsafe {
277                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
278                 }
279             }
280             _ => {
281                 // For non-immediate arguments the callee gets its own copy of
282                 // the value on the stack, so there are no aliases
283                 if !type_is_immediate(ccx, arg_ty) {
284                     unsafe {
285                         llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
286                         llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
287                     }
288                 }
289             }
290         }
291     }
292
293     // The out pointer will never alias with any other pointers, as the object only exists at a
294     // language level after the call. It can also be tagged with SRet to indicate that it is
295     // guaranteed to point to a usable block of memory for the type.
296     if uses_outptr {
297         unsafe {
298             let outptr = llvm::LLVMGetParam(llfn, 0);
299             llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
300             llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
301         }
302     }
303
304     llfn
305 }
306
307 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
308                              inputs: &[ty::t], output: ty::t,
309                              name: &str) -> ValueRef {
310     let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
311     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
312     llfn
313 }
314
315 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
316                         name: &str, ty: Type) -> ValueRef {
317     match externs.find_equiv(&name) {
318         Some(n) => return *n,
319         None => ()
320     }
321     unsafe {
322         let c = name.with_c_str(|buf| {
323             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
324         });
325         externs.insert(name.to_owned(), c);
326         return c;
327     }
328 }
329
330 // Returns a pointer to the body for the box. The box may be an opaque
331 // box. The result will be casted to the type of body_t, if it is statically
332 // known.
333 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
334     let _icx = push_ctxt("at_box_body");
335     let ccx = bcx.ccx();
336     let ty = Type::at_box(ccx, type_of(ccx, body_t));
337     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
338     GEPi(bcx, boxptr, [0u, abi::box_field_body])
339 }
340
341 // malloc_raw_dyn: allocates a box to contain a given type, but with a
342 // potentially dynamic size.
343 pub fn malloc_raw_dyn<'a>(
344                       bcx: &'a Block<'a>,
345                       t: ty::t,
346                       heap: heap,
347                       size: ValueRef)
348                       -> Result<'a> {
349     let _icx = push_ctxt("malloc_raw");
350     let ccx = bcx.ccx();
351
352     fn require_alloc_fn(bcx: &Block, t: ty::t, it: LangItem) -> ast::DefId {
353         let li = &bcx.tcx().lang_items;
354         match li.require(it) {
355             Ok(id) => id,
356             Err(s) => {
357                 bcx.tcx().sess.fatal(format!("allocation of `{}` {}",
358                                           bcx.ty_to_str(t), s));
359             }
360         }
361     }
362
363     if heap == heap_exchange {
364         let llty_value = type_of::type_of(ccx, t);
365
366         // Allocate space:
367         let r = callee::trans_lang_call(
368             bcx,
369             require_alloc_fn(bcx, t, ExchangeMallocFnLangItem),
370             [size],
371             None);
372         rslt(r.bcx, PointerCast(r.bcx, r.val, llty_value.ptr_to()))
373     } else {
374         // we treat ~fn as @ here, which isn't ideal
375         let langcall = match heap {
376             heap_managed => {
377                 require_alloc_fn(bcx, t, MallocFnLangItem)
378             }
379             heap_exchange_closure => {
380                 require_alloc_fn(bcx, t, ClosureExchangeMallocFnLangItem)
381             }
382             _ => fail!("heap_exchange already handled")
383         };
384
385         // Grab the TypeRef type of box_ptr_ty.
386         let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
387         let llty = type_of(ccx, box_ptr_ty);
388         let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
389
390         // Allocate space:
391         let drop_glue = glue::get_drop_glue(ccx, t);
392         let r = callee::trans_lang_call(
393             bcx,
394             langcall,
395             [PointerCast(bcx, drop_glue, Type::glue_fn(Type::i8p()).ptr_to()), size, llalign],
396             None);
397         rslt(r.bcx, PointerCast(r.bcx, r.val, llty))
398     }
399 }
400
401 // malloc_raw: expects an unboxed type and returns a pointer to
402 // enough space for a box of that type.  This includes a rust_opaque_box
403 // header.
404 pub fn malloc_raw<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
405                   -> Result<'a> {
406     let ty = type_of(bcx.ccx(), t);
407     let size = llsize_of(bcx.ccx(), ty);
408     malloc_raw_dyn(bcx, t, heap, size)
409 }
410
411 pub struct MallocResult<'a> {
412     bcx: &'a Block<'a>,
413     smart_ptr: ValueRef,
414     body: ValueRef
415 }
416
417 // malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a smart
418 // pointer, and pulls out the body
419 pub fn malloc_general_dyn<'a>(
420                           bcx: &'a Block<'a>,
421                           t: ty::t,
422                           heap: heap,
423                           size: ValueRef)
424                           -> MallocResult<'a> {
425     assert!(heap != heap_exchange);
426     let _icx = push_ctxt("malloc_general");
427     let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
428     let body = GEPi(bcx, llbox, [0u, abi::box_field_body]);
429
430     MallocResult {
431         bcx: bcx,
432         smart_ptr: llbox,
433         body: body,
434     }
435 }
436
437 pub fn malloc_general<'a>(bcx: &'a Block<'a>, t: ty::t, heap: heap)
438                       -> MallocResult<'a> {
439     let ty = type_of(bcx.ccx(), t);
440     assert!(heap != heap_exchange);
441     malloc_general_dyn(bcx, t, heap, llsize_of(bcx.ccx(), ty))
442 }
443
444 // Type descriptor and type glue stuff
445
446 pub fn get_tydesc_simple(ccx: &CrateContext, t: ty::t) -> ValueRef {
447     get_tydesc(ccx, t).tydesc
448 }
449
450 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> @tydesc_info {
451     {
452         let tydescs = ccx.tydescs.borrow();
453         match tydescs.get().find(&t) {
454             Some(&inf) => return inf,
455             _ => { }
456         }
457     }
458
459     ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
460     let inf = glue::declare_tydesc(ccx, t);
461
462     let mut tydescs = ccx.tydescs.borrow_mut();
463     tydescs.get().insert(t, inf);
464     return inf;
465 }
466
467 pub fn set_optimize_for_size(f: ValueRef) {
468     lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
469 }
470
471 pub fn set_no_inline(f: ValueRef) {
472     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
473 }
474
475 pub fn set_no_unwind(f: ValueRef) {
476     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
477 }
478
479 // Tell LLVM to emit the information necessary to unwind the stack for the
480 // function f.
481 pub fn set_uwtable(f: ValueRef) {
482     lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
483 }
484
485 pub fn set_inline_hint(f: ValueRef) {
486     lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
487 }
488
489 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
490     use syntax::attr::*;
491     // Set the inline hint if there is one
492     match find_inline_attr(attrs) {
493         InlineHint   => set_inline_hint(llfn),
494         InlineAlways => set_always_inline(llfn),
495         InlineNever  => set_no_inline(llfn),
496         InlineNone   => { /* fallthrough */ }
497     }
498
499     // Add the no-split-stack attribute if requested
500     if contains_name(attrs, "no_split_stack") {
501         set_no_split_stack(llfn);
502     }
503
504     if contains_name(attrs, "cold") {
505         unsafe { llvm::LLVMAddColdAttribute(llfn) }
506     }
507 }
508
509 pub fn set_always_inline(f: ValueRef) {
510     lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
511 }
512
513 pub fn set_no_split_stack(f: ValueRef) {
514     "no-split-stack".with_c_str(|buf| {
515         unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
516     })
517 }
518
519 // Double-check that we never ask LLVM to declare the same symbol twice. It
520 // silently mangles such symbols, breaking our linkage model.
521 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
522     let mut all_llvm_symbols = ccx.all_llvm_symbols.borrow_mut();
523     if all_llvm_symbols.get().contains(&sym) {
524         ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
525     }
526     all_llvm_symbols.get().insert(sym);
527 }
528
529
530 pub fn get_res_dtor(ccx: @CrateContext,
531                     did: ast::DefId,
532                     parent_id: ast::DefId,
533                     substs: &[ty::t])
534                  -> ValueRef {
535     let _icx = push_ctxt("trans_res_dtor");
536     let did = if did.krate != ast::LOCAL_CRATE {
537         inline::maybe_instantiate_inline(ccx, did)
538     } else {
539         did
540     };
541     if !substs.is_empty() {
542         assert_eq!(did.krate, ast::LOCAL_CRATE);
543         let tsubsts = ty::substs {
544             regions: ty::ErasedRegions,
545             self_ty: None,
546             tps: substs.to_owned()
547         };
548
549         let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx, did.node, &tsubsts);
550         let (val, _) = monomorphize::monomorphic_fn(ccx, did, &tsubsts, vtables, None, None);
551
552         val
553     } else if did.krate == ast::LOCAL_CRATE {
554         get_item_val(ccx, did.node)
555     } else {
556         let tcx = ccx.tcx;
557         let name = csearch::get_symbol(ccx.sess.cstore, did);
558         let class_ty = ty::subst_tps(tcx,
559                                      substs,
560                                      None,
561                                      ty::lookup_item_type(tcx, parent_id).ty);
562         let llty = type_of_dtor(ccx, class_ty);
563
564         {
565             let mut externs = ccx.externs.borrow_mut();
566             get_extern_fn(externs.get(), ccx.llmod, name,
567                           lib::llvm::CCallConv, llty, ty::mk_nil())
568         }
569     }
570 }
571
572 // Structural comparison: a rather involved form of glue.
573 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
574     if cx.sess.opts.cg.save_temps {
575         s.with_c_str(|buf| {
576             unsafe {
577                 llvm::LLVMSetValueName(v, buf)
578             }
579         })
580     }
581 }
582
583
584 // Used only for creating scalar comparison glue.
585 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
586
587 // NB: This produces an i1, not a Rust bool (i8).
588 pub fn compare_scalar_types<'a>(
589                             cx: &'a Block<'a>,
590                             lhs: ValueRef,
591                             rhs: ValueRef,
592                             t: ty::t,
593                             op: ast::BinOp)
594                             -> Result<'a> {
595     let f = |a| rslt(cx, compare_scalar_values(cx, lhs, rhs, a, op));
596
597     match ty::get(t).sty {
598         ty::ty_nil => f(nil_type),
599         ty::ty_bool | ty::ty_ptr(_) |
600         ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
601         ty::ty_int(_) => f(signed_int),
602         ty::ty_float(_) => f(floating_point),
603             // Should never get here, because t is scalar.
604         _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
605     }
606 }
607
608
609 // A helper function to do the actual comparison of scalar values.
610 pub fn compare_scalar_values<'a>(
611                              cx: &'a Block<'a>,
612                              lhs: ValueRef,
613                              rhs: ValueRef,
614                              nt: scalar_type,
615                              op: ast::BinOp)
616                              -> ValueRef {
617     let _icx = push_ctxt("compare_scalar_values");
618     fn die(cx: &Block) -> ! {
619         cx.tcx().sess.bug("compare_scalar_values: must be a\
620                            comparison operator");
621     }
622     match nt {
623       nil_type => {
624         // We don't need to do actual comparisons for nil.
625         // () == () holds but () < () does not.
626         match op {
627           ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(true),
628           ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(false),
629           // refinements would be nice
630           _ => die(cx)
631         }
632       }
633       floating_point => {
634         let cmp = match op {
635           ast::BiEq => lib::llvm::RealOEQ,
636           ast::BiNe => lib::llvm::RealUNE,
637           ast::BiLt => lib::llvm::RealOLT,
638           ast::BiLe => lib::llvm::RealOLE,
639           ast::BiGt => lib::llvm::RealOGT,
640           ast::BiGe => lib::llvm::RealOGE,
641           _ => die(cx)
642         };
643         return FCmp(cx, cmp, lhs, rhs);
644       }
645       signed_int => {
646         let cmp = match op {
647           ast::BiEq => lib::llvm::IntEQ,
648           ast::BiNe => lib::llvm::IntNE,
649           ast::BiLt => lib::llvm::IntSLT,
650           ast::BiLe => lib::llvm::IntSLE,
651           ast::BiGt => lib::llvm::IntSGT,
652           ast::BiGe => lib::llvm::IntSGE,
653           _ => die(cx)
654         };
655         return ICmp(cx, cmp, lhs, rhs);
656       }
657       unsigned_int => {
658         let cmp = match op {
659           ast::BiEq => lib::llvm::IntEQ,
660           ast::BiNe => lib::llvm::IntNE,
661           ast::BiLt => lib::llvm::IntULT,
662           ast::BiLe => lib::llvm::IntULE,
663           ast::BiGt => lib::llvm::IntUGT,
664           ast::BiGe => lib::llvm::IntUGE,
665           _ => die(cx)
666         };
667         return ICmp(cx, cmp, lhs, rhs);
668       }
669     }
670 }
671
672 pub type val_and_ty_fn<'r,'b> =
673     'r |&'b Block<'b>, ValueRef, ty::t| -> &'b Block<'b>;
674
675 pub fn load_inbounds<'a>(cx: &'a Block<'a>, p: ValueRef, idxs: &[uint])
676                      -> ValueRef {
677     return Load(cx, GEPi(cx, p, idxs));
678 }
679
680 pub fn store_inbounds<'a>(
681                       cx: &'a Block<'a>,
682                       v: ValueRef,
683                       p: ValueRef,
684                       idxs: &[uint]) {
685     Store(cx, v, GEPi(cx, p, idxs));
686 }
687
688 // Iterates through the elements of a structural type.
689 pub fn iter_structural_ty<'r,
690                           'b>(
691                           cx: &'b Block<'b>,
692                           av: ValueRef,
693                           t: ty::t,
694                           f: val_and_ty_fn<'r,'b>)
695                           -> &'b Block<'b> {
696     let _icx = push_ctxt("iter_structural_ty");
697
698     fn iter_variant<'r,
699                     'b>(
700                     cx: &'b Block<'b>,
701                     repr: &adt::Repr,
702                     av: ValueRef,
703                     variant: @ty::VariantInfo,
704                     tps: &[ty::t],
705                     f: val_and_ty_fn<'r,'b>)
706                     -> &'b Block<'b> {
707         let _icx = push_ctxt("iter_variant");
708         let tcx = cx.tcx();
709         let mut cx = cx;
710
711         for (i, &arg) in variant.args.iter().enumerate() {
712             cx = f(cx,
713                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
714                    ty::subst_tps(tcx, tps, None, arg));
715         }
716         return cx;
717     }
718
719     let mut cx = cx;
720     match ty::get(t).sty {
721       ty::ty_struct(..) => {
722           let repr = adt::represent_type(cx.ccx(), t);
723           expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
724               for (i, field_ty) in field_tys.iter().enumerate() {
725                   let llfld_a = adt::trans_field_ptr(cx, repr, av, discr, i);
726                   cx = f(cx, llfld_a, field_ty.mt.ty);
727               }
728           })
729       }
730       ty::ty_str(ty::vstore_fixed(_)) |
731       ty::ty_vec(_, ty::vstore_fixed(_)) => {
732         let (base, len) = tvec::get_base_and_byte_len(cx, av, t);
733         cx = tvec::iter_vec_raw(cx, base, t, len, f);
734       }
735       ty::ty_tup(ref args) => {
736           let repr = adt::represent_type(cx.ccx(), t);
737           for (i, arg) in args.iter().enumerate() {
738               let llfld_a = adt::trans_field_ptr(cx, repr, av, 0, i);
739               cx = f(cx, llfld_a, *arg);
740           }
741       }
742       ty::ty_enum(tid, ref substs) => {
743           let fcx = cx.fcx;
744           let ccx = fcx.ccx;
745
746           let repr = adt::represent_type(ccx, t);
747           let variants = ty::enum_variants(ccx.tcx, tid);
748           let n_variants = (*variants).len();
749
750           // NB: we must hit the discriminant first so that structural
751           // comparison know not to proceed when the discriminants differ.
752
753           match adt::trans_switch(cx, repr, av) {
754               (_match::single, None) => {
755                   cx = iter_variant(cx, repr, av, variants[0],
756                                     substs.tps, f);
757               }
758               (_match::switch, Some(lldiscrim_a)) => {
759                   cx = f(cx, lldiscrim_a, ty::mk_int());
760                   let unr_cx = fcx.new_temp_block("enum-iter-unr");
761                   Unreachable(unr_cx);
762                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
763                                         n_variants);
764                   let next_cx = fcx.new_temp_block("enum-iter-next");
765
766                   for variant in (*variants).iter() {
767                       let variant_cx =
768                           fcx.new_temp_block(~"enum-iter-variant-" +
769                                              variant.disr_val.to_str());
770                       match adt::trans_case(cx, repr, variant.disr_val) {
771                           _match::single_result(r) => {
772                               AddCase(llswitch, r.val, variant_cx.llbb)
773                           }
774                           _ => ccx.sess.unimpl("value from adt::trans_case \
775                                                 in iter_structural_ty")
776                       }
777                       let variant_cx =
778                           iter_variant(variant_cx, repr, av, *variant,
779                                        substs.tps, |x,y,z| f(x,y,z));
780                       Br(variant_cx, next_cx.llbb);
781                   }
782                   cx = next_cx;
783               }
784               _ => ccx.sess.unimpl("value from adt::trans_switch \
785                                     in iter_structural_ty")
786           }
787       }
788       _ => cx.sess().unimpl("type in iter_structural_ty")
789     }
790     return cx;
791 }
792
793 pub fn cast_shift_expr_rhs<'a>(
794                            cx: &'a Block<'a>,
795                            op: ast::BinOp,
796                            lhs: ValueRef,
797                            rhs: ValueRef)
798                            -> ValueRef {
799     cast_shift_rhs(op, lhs, rhs,
800                    |a,b| Trunc(cx, a, b),
801                    |a,b| ZExt(cx, a, b))
802 }
803
804 pub fn cast_shift_const_rhs(op: ast::BinOp,
805                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
806     cast_shift_rhs(op, lhs, rhs,
807                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
808                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
809 }
810
811 pub fn cast_shift_rhs(op: ast::BinOp,
812                       lhs: ValueRef,
813                       rhs: ValueRef,
814                       trunc: |ValueRef, Type| -> ValueRef,
815                       zext: |ValueRef, Type| -> ValueRef)
816                       -> ValueRef {
817     // Shifts may have any size int on the rhs
818     unsafe {
819         if ast_util::is_shift_binop(op) {
820             let mut rhs_llty = val_ty(rhs);
821             let mut lhs_llty = val_ty(lhs);
822             if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
823             if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
824             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
825             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
826             if lhs_sz < rhs_sz {
827                 trunc(rhs, lhs_llty)
828             } else if lhs_sz > rhs_sz {
829                 // FIXME (#1877: If shifting by negative
830                 // values becomes not undefined then this is wrong.
831                 zext(rhs, lhs_llty)
832             } else {
833                 rhs
834             }
835         } else {
836             rhs
837         }
838     }
839 }
840
841 pub fn fail_if_zero<'a>(
842                     cx: &'a Block<'a>,
843                     span: Span,
844                     divrem: ast::BinOp,
845                     rhs: ValueRef,
846                     rhs_t: ty::t)
847                     -> &'a Block<'a> {
848     let text = if divrem == ast::BiDiv {
849         "attempted to divide by zero"
850     } else {
851         "attempted remainder with a divisor of zero"
852     };
853     let is_zero = match ty::get(rhs_t).sty {
854       ty::ty_int(t) => {
855         let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
856         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
857       }
858       ty::ty_uint(t) => {
859         let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
860         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
861       }
862       _ => {
863         cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
864                           ty_to_str(cx.ccx().tcx, rhs_t));
865       }
866     };
867     with_cond(cx, is_zero, |bcx| {
868         controlflow::trans_fail(bcx, span, InternedString::new(text))
869     })
870 }
871
872 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
873     let name = csearch::get_symbol(ccx.sess.cstore, did);
874     match ty::get(t).sty {
875         ty::ty_bare_fn(ref fn_ty) => {
876             match fn_ty.abis.for_target(ccx.sess.targ_cfg.os,
877                                         ccx.sess.targ_cfg.arch) {
878                 Some(Rust) | Some(RustIntrinsic) => {
879                     get_extern_rust_fn(ccx, fn_ty.sig.inputs, fn_ty.sig.output, name, did)
880                 }
881                 Some(..) | None => {
882                     let c = foreign::llvm_calling_convention(ccx, fn_ty.abis);
883                     let cconv = c.unwrap_or(lib::llvm::CCallConv);
884                     let llty = type_of_fn_from_ty(ccx, t);
885                     let mut externs = ccx.externs.borrow_mut();
886                     get_extern_fn(externs.get(), ccx.llmod, name,
887                                   cconv, llty, fn_ty.sig.output)
888                 }
889             }
890         }
891         ty::ty_closure(ref f) => {
892             get_extern_rust_fn(ccx, f.sig.inputs, f.sig.output, name, did)
893         }
894         _ => {
895             let llty = type_of(ccx, t);
896             let mut externs = ccx.externs.borrow_mut();
897             get_extern_const(externs.get(), ccx.llmod, name, llty)
898         }
899     }
900 }
901
902 pub fn invoke<'a>(
903               bcx: &'a Block<'a>,
904               llfn: ValueRef,
905               llargs: ~[ValueRef],
906               attributes: &[(uint, lib::llvm::Attribute)],
907               call_info: Option<NodeInfo>)
908               -> (ValueRef, &'a Block<'a>) {
909     let _icx = push_ctxt("invoke_");
910     if bcx.unreachable.get() {
911         return (C_null(Type::i8()), bcx);
912     }
913
914     match bcx.opt_node_id {
915         None => {
916             debug!("invoke at ???");
917         }
918         Some(id) => {
919             debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
920         }
921     }
922
923     if need_invoke(bcx) {
924         debug!("invoking {} at {}", llfn, bcx.llbb);
925         for &llarg in llargs.iter() {
926             debug!("arg: {}", llarg);
927         }
928         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
929         let landing_pad = bcx.fcx.get_landing_pad();
930
931         match call_info {
932             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
933             None => debuginfo::clear_source_location(bcx.fcx)
934         };
935
936         let llresult = Invoke(bcx,
937                               llfn,
938                               llargs,
939                               normal_bcx.llbb,
940                               landing_pad,
941                               attributes);
942         return (llresult, normal_bcx);
943     } else {
944         debug!("calling {} at {}", llfn, bcx.llbb);
945         for &llarg in llargs.iter() {
946             debug!("arg: {}", llarg);
947         }
948
949         match call_info {
950             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
951             None => debuginfo::clear_source_location(bcx.fcx)
952         };
953
954         let llresult = Call(bcx, llfn, llargs, attributes);
955         return (llresult, bcx);
956     }
957 }
958
959 pub fn need_invoke(bcx: &Block) -> bool {
960     if bcx.ccx().sess.no_landing_pads() {
961         return false;
962     }
963
964     // Avoid using invoke if we are already inside a landing pad.
965     if bcx.is_lpad {
966         return false;
967     }
968
969     bcx.fcx.needs_invoke()
970 }
971
972 pub fn do_spill(bcx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
973     if ty::type_is_bot(t) {
974         return C_null(Type::i8p());
975     }
976     let llptr = alloc_ty(bcx, t, "");
977     Store(bcx, v, llptr);
978     return llptr;
979 }
980
981 // Since this function does *not* root, it is the caller's responsibility to
982 // ensure that the referent is pointed to by a root.
983 pub fn do_spill_noroot(cx: &Block, v: ValueRef) -> ValueRef {
984     let llptr = alloca(cx, val_ty(v), "");
985     Store(cx, v, llptr);
986     return llptr;
987 }
988
989 pub fn spill_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
990     let _icx = push_ctxt("spill_if_immediate");
991     if type_is_immediate(cx.ccx(), t) { return do_spill(cx, v, t); }
992     return v;
993 }
994
995 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
996     let _icx = push_ctxt("load_if_immediate");
997     if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
998     return v;
999 }
1000
1001 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
1002     match local.pat.node {
1003         ast::PatWild => true, _ => false
1004     }
1005 }
1006
1007 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
1008                   -> &'a Block<'a> {
1009
1010     debug!("init_local(bcx={}, local.id={:?})",
1011            bcx.to_str(), local.id);
1012     let _indenter = indenter();
1013
1014     let _icx = push_ctxt("init_local");
1015
1016     if ignore_lhs(bcx, local) {
1017         // Handle let _ = e; just like e;
1018         match local.init {
1019             Some(init) => {
1020               return expr::trans_into(bcx, init, expr::Ignore);
1021             }
1022             None => { return bcx; }
1023         }
1024     }
1025
1026     _match::store_local(bcx, local)
1027 }
1028
1029 pub fn raw_block<'a>(
1030                  fcx: &'a FunctionContext<'a>,
1031                  is_lpad: bool,
1032                  llbb: BasicBlockRef)
1033                  -> &'a Block<'a> {
1034     Block::new(llbb, is_lpad, None, fcx)
1035 }
1036
1037 pub fn block_locals(b: &ast::Block, it: |@ast::Local|) {
1038     for s in b.stmts.iter() {
1039         match s.node {
1040           ast::StmtDecl(d, _) => {
1041             match d.node {
1042               ast::DeclLocal(ref local) => it(*local),
1043               _ => {} /* fall through */
1044             }
1045           }
1046           _ => {} /* fall through */
1047         }
1048     }
1049 }
1050
1051 pub fn with_cond<'a>(
1052                  bcx: &'a Block<'a>,
1053                  val: ValueRef,
1054                  f: |&'a Block<'a>| -> &'a Block<'a>)
1055                  -> &'a Block<'a> {
1056     let _icx = push_ctxt("with_cond");
1057     let fcx = bcx.fcx;
1058     let next_cx = fcx.new_temp_block("next");
1059     let cond_cx = fcx.new_temp_block("cond");
1060     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
1061     let after_cx = f(cond_cx);
1062     if !after_cx.terminated.get() {
1063         Br(after_cx, next_cx.llbb);
1064     }
1065     next_cx
1066 }
1067
1068 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1069     let _icx = push_ctxt("call_memcpy");
1070     let ccx = cx.ccx();
1071     let key = match ccx.sess.targ_cfg.arch {
1072         X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1073         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1074     };
1075     let memcpy = ccx.intrinsics.get_copy(&key);
1076     let src_ptr = PointerCast(cx, src, Type::i8p());
1077     let dst_ptr = PointerCast(cx, dst, Type::i8p());
1078     let size = IntCast(cx, n_bytes, ccx.int_type);
1079     let align = C_i32(align as i32);
1080     let volatile = C_i1(false);
1081     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1082 }
1083
1084 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1085     let _icx = push_ctxt("memcpy_ty");
1086     let ccx = bcx.ccx();
1087     if ty::type_is_structural(t) {
1088         let llty = type_of::type_of(ccx, t);
1089         let llsz = llsize_of(ccx, llty);
1090         let llalign = llalign_of_min(ccx, llty);
1091         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1092     } else {
1093         Store(bcx, Load(bcx, src), dst);
1094     }
1095 }
1096
1097 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1098     if cx.unreachable.get() { return; }
1099     let _icx = push_ctxt("zero_mem");
1100     let bcx = cx;
1101     let ccx = cx.ccx();
1102     let llty = type_of::type_of(ccx, t);
1103     memzero(&B(bcx), llptr, llty);
1104 }
1105
1106 // Always use this function instead of storing a zero constant to the memory
1107 // in question. If you store a zero constant, LLVM will drown in vreg
1108 // allocation for large data structures, and the generated code will be
1109 // awful. (A telltale sign of this is large quantities of
1110 // `mov [byte ptr foo],0` in the generated code.)
1111 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1112     let _icx = push_ctxt("memzero");
1113     let ccx = b.ccx;
1114
1115     let intrinsic_key = match ccx.sess.targ_cfg.arch {
1116         X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1117         X86_64 => "llvm.memset.p0i8.i64"
1118     };
1119
1120     let llintrinsicfn = ccx.intrinsics.get_copy(&intrinsic_key);
1121     let llptr = b.pointercast(llptr, Type::i8().ptr_to());
1122     let llzeroval = C_u8(0);
1123     let size = machine::llsize_of(ccx, ty);
1124     let align = C_i32(llalign_of_min(ccx, ty) as i32);
1125     let volatile = C_i1(false);
1126     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1127 }
1128
1129 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1130     let _icx = push_ctxt("alloc_ty");
1131     let ccx = bcx.ccx();
1132     let ty = type_of::type_of(ccx, t);
1133     assert!(!ty::type_has_params(t));
1134     let val = alloca(bcx, ty, name);
1135     return val;
1136 }
1137
1138 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1139     alloca_maybe_zeroed(cx, ty, name, false)
1140 }
1141
1142 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1143     let _icx = push_ctxt("alloca");
1144     if cx.unreachable.get() {
1145         unsafe {
1146             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1147         }
1148     }
1149     debuginfo::clear_source_location(cx.fcx);
1150     let p = Alloca(cx, ty, name);
1151     if zero {
1152         let b = cx.fcx.ccx.builder();
1153         b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1154         memzero(&b, p, ty);
1155     }
1156     p
1157 }
1158
1159 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1160     let _icx = push_ctxt("arrayalloca");
1161     if cx.unreachable.get() {
1162         unsafe {
1163             return llvm::LLVMGetUndef(ty.to_ref());
1164         }
1165     }
1166     debuginfo::clear_source_location(cx.fcx);
1167     return ArrayAlloca(cx, ty, v);
1168 }
1169
1170 pub struct BasicBlocks {
1171     sa: BasicBlockRef,
1172 }
1173
1174 pub fn mk_staticallocas_basic_block(llfn: ValueRef) -> BasicBlockRef {
1175     unsafe {
1176         let cx = task_llcx();
1177         "static_allocas".with_c_str(|buf| {
1178             llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1179         })
1180     }
1181 }
1182
1183 pub fn mk_return_basic_block(llfn: ValueRef) -> BasicBlockRef {
1184     unsafe {
1185         let cx = task_llcx();
1186         "return".with_c_str(|buf| {
1187             llvm::LLVMAppendBasicBlockInContext(cx, llfn, buf)
1188         })
1189     }
1190 }
1191
1192 // Creates and returns space for, or returns the argument representing, the
1193 // slot where the return value of the function must go.
1194 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1195                            -> ValueRef {
1196     unsafe {
1197         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1198             llvm::LLVMGetParam(fcx.llfn, 0)
1199         } else {
1200             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1201             let bcx = fcx.entry_bcx.get().unwrap();
1202             Alloca(bcx, lloutputtype, "__make_return_pointer")
1203         }
1204     }
1205 }
1206
1207 // NB: must keep 4 fns in sync:
1208 //
1209 //  - type_of_fn
1210 //  - create_datums_for_fn_args.
1211 //  - new_fn_ctxt
1212 //  - trans_args
1213 //
1214 // Be warned! You must call `init_function` before doing anything with the
1215 // returned function context.
1216 pub fn new_fn_ctxt<'a>(ccx: @CrateContext,
1217                        llfndecl: ValueRef,
1218                        id: ast::NodeId,
1219                        has_env: bool,
1220                        output_type: ty::t,
1221                        param_substs: Option<@param_substs>,
1222                        sp: Option<Span>,
1223                        block_arena: &'a TypedArena<Block<'a>>)
1224                        -> FunctionContext<'a> {
1225     for p in param_substs.iter() { p.validate(); }
1226
1227     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1228            if id == -1 { ~"" } else { ccx.tcx.map.path_to_str(id) },
1229            id, param_substs.repr(ccx.tcx));
1230
1231     let substd_output_type = match param_substs {
1232         None => output_type,
1233         Some(substs) => {
1234             ty::subst_tps(ccx.tcx, substs.tys, substs.self_ty, output_type)
1235         }
1236     };
1237     let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1238     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1239
1240     let mut fcx = FunctionContext {
1241           llfn: llfndecl,
1242           llenv: None,
1243           llretptr: Cell::new(None),
1244           entry_bcx: RefCell::new(None),
1245           alloca_insert_pt: Cell::new(None),
1246           llreturn: Cell::new(None),
1247           personality: Cell::new(None),
1248           caller_expects_out_pointer: uses_outptr,
1249           llargs: RefCell::new(NodeMap::new()),
1250           lllocals: RefCell::new(NodeMap::new()),
1251           llupvars: RefCell::new(NodeMap::new()),
1252           id: id,
1253           param_substs: param_substs,
1254           span: sp,
1255           block_arena: block_arena,
1256           ccx: ccx,
1257           debug_context: debug_context,
1258           scopes: RefCell::new(~[])
1259     };
1260
1261     if has_env {
1262         fcx.llenv = Some(unsafe {
1263             llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1264         });
1265     }
1266
1267     fcx
1268 }
1269
1270 /// Performs setup on a newly created function, creating the entry scope block
1271 /// and allocating space for the return pointer.
1272 pub fn init_function<'a>(
1273                      fcx: &'a FunctionContext<'a>,
1274                      skip_retptr: bool,
1275                      output_type: ty::t,
1276                      param_substs: Option<@param_substs>) {
1277     let entry_bcx = fcx.new_temp_block("entry-block");
1278
1279     fcx.entry_bcx.set(Some(entry_bcx));
1280
1281     // Use a dummy instruction as the insertion point for all allocas.
1282     // This is later removed in FunctionContext::cleanup.
1283     fcx.alloca_insert_pt.set(Some(unsafe {
1284         Load(entry_bcx, C_null(Type::i8p()));
1285         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1286     }));
1287
1288     let substd_output_type = match param_substs {
1289         None => output_type,
1290         Some(substs) => {
1291             ty::subst_tps(fcx.ccx.tcx,
1292                           substs.tys,
1293                           substs.self_ty,
1294                           output_type)
1295         }
1296     };
1297
1298     if !return_type_is_void(fcx.ccx, substd_output_type) {
1299         // If the function returns nil/bot, there is no real return
1300         // value, so do not set `llretptr`.
1301         if !skip_retptr || fcx.caller_expects_out_pointer {
1302             // Otherwise, we normally allocate the llretptr, unless we
1303             // have been instructed to skip it for immediate return
1304             // values.
1305             fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1306         }
1307     }
1308 }
1309
1310 // NB: must keep 4 fns in sync:
1311 //
1312 //  - type_of_fn
1313 //  - create_datums_for_fn_args.
1314 //  - new_fn_ctxt
1315 //  - trans_args
1316
1317 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1318     use middle::trans::datum::{ByRef, ByValue};
1319
1320     datum::Rvalue {
1321         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1322     }
1323 }
1324
1325 // work around bizarre resolve errors
1326 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1327 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1328
1329 // create_datums_for_fn_args: creates rvalue datums for each of the
1330 // incoming function arguments. These will later be stored into
1331 // appropriate lvalue datums.
1332 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1333                                  arg_tys: &[ty::t])
1334                                  -> ~[RvalueDatum] {
1335     let _icx = push_ctxt("create_datums_for_fn_args");
1336
1337     // Return an array wrapping the ValueRefs that we get from
1338     // llvm::LLVMGetParam for each argument into datums.
1339     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1340         let llarg = unsafe {
1341             llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1342         };
1343         datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1344     }).collect()
1345 }
1346
1347 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1348                             arg_scope: cleanup::CustomScopeIndex,
1349                             bcx: &'a Block<'a>,
1350                             args: &[ast::Arg],
1351                             arg_datums: ~[RvalueDatum])
1352                             -> &'a Block<'a> {
1353     debug!("copy_args_to_allocas");
1354
1355     let _icx = push_ctxt("copy_args_to_allocas");
1356     let mut bcx = bcx;
1357
1358     let arg_scope_id = cleanup::CustomScope(arg_scope);
1359
1360     for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1361         // For certain mode/type combinations, the raw llarg values are passed
1362         // by value.  However, within the fn body itself, we want to always
1363         // have all locals and arguments be by-ref so that we can cancel the
1364         // cleanup and for better interaction with LLVM's debug info.  So, if
1365         // the argument would be passed by value, we store it into an alloca.
1366         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1367         // the event it's not truly needed.
1368
1369         bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1370
1371         if fcx.ccx.sess.opts.debuginfo == FullDebugInfo {
1372             debuginfo::create_argument_metadata(bcx, &args[i]);
1373         }
1374     }
1375
1376     bcx
1377 }
1378
1379 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1380 // and builds the return block.
1381 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1382                      last_bcx: &'a Block<'a>) {
1383     let _icx = push_ctxt("finish_fn");
1384
1385     let ret_cx = match fcx.llreturn.get() {
1386         Some(llreturn) => {
1387             if !last_bcx.terminated.get() {
1388                 Br(last_bcx, llreturn);
1389             }
1390             raw_block(fcx, false, llreturn)
1391         }
1392         None => last_bcx
1393     };
1394     build_return_block(fcx, ret_cx);
1395     debuginfo::clear_source_location(fcx);
1396     fcx.cleanup();
1397 }
1398
1399 // Builds the return block for a function.
1400 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1401     // Return the value if this function immediate; otherwise, return void.
1402     if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1403         return RetVoid(ret_cx);
1404     }
1405
1406     let retptr = Value(fcx.llretptr.get().unwrap());
1407     let retval = match retptr.get_dominating_store(ret_cx) {
1408         // If there's only a single store to the ret slot, we can directly return
1409         // the value that was stored and omit the store and the alloca
1410         Some(s) => {
1411             let retval = s.get_operand(0).unwrap().get();
1412             s.erase_from_parent();
1413
1414             if retptr.has_no_uses() {
1415                 retptr.erase_from_parent();
1416             }
1417
1418             retval
1419         }
1420         // Otherwise, load the return value from the ret slot
1421         None => Load(ret_cx, fcx.llretptr.get().unwrap())
1422     };
1423
1424
1425     Ret(ret_cx, retval);
1426 }
1427
1428 // trans_closure: Builds an LLVM function out of a source function.
1429 // If the function closes over its environment a closure will be
1430 // returned.
1431 pub fn trans_closure<'a>(ccx: @CrateContext,
1432                          decl: &ast::FnDecl,
1433                          body: &ast::Block,
1434                          llfndecl: ValueRef,
1435                          param_substs: Option<@param_substs>,
1436                          id: ast::NodeId,
1437                          _attributes: &[ast::Attribute],
1438                          output_type: ty::t,
1439                          maybe_load_env: <'b> |&'b Block<'b>| -> &'b Block<'b>) {
1440     ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1441
1442     let _icx = push_ctxt("trans_closure");
1443     set_uwtable(llfndecl);
1444
1445     debug!("trans_closure(..., param_substs={})",
1446            param_substs.repr(ccx.tcx));
1447
1448     let has_env = match ty::get(ty::node_id_to_type(ccx.tcx, id)).sty {
1449         ty::ty_closure(_) => true,
1450         _ => false
1451     };
1452
1453     let arena = TypedArena::new();
1454     let fcx = new_fn_ctxt(ccx,
1455                           llfndecl,
1456                           id,
1457                           has_env,
1458                           output_type,
1459                           param_substs,
1460                           Some(body.span),
1461                           &arena);
1462     init_function(&fcx, false, output_type, param_substs);
1463
1464     // cleanup scope for the incoming arguments
1465     let arg_scope = fcx.push_custom_cleanup_scope();
1466
1467     // Create the first basic block in the function and keep a handle on it to
1468     //  pass to finish_fn later.
1469     let bcx_top = fcx.entry_bcx.get().unwrap();
1470     let mut bcx = bcx_top;
1471     let block_ty = node_id_type(bcx, body.id);
1472
1473     // Set up arguments to the function.
1474     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1475     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys);
1476
1477     bcx = copy_args_to_allocas(&fcx,
1478                                arg_scope,
1479                                bcx,
1480                                decl.inputs.as_slice(),
1481                                arg_datums);
1482
1483     bcx = maybe_load_env(bcx);
1484
1485     // Up until here, IR instructions for this function have explicitly not been annotated with
1486     // source code location, so we don't step into call setup code. From here on, source location
1487     // emitting should be enabled.
1488     debuginfo::start_emitting_source_locations(&fcx);
1489
1490     let dest = match fcx.llretptr.get() {
1491         Some(e) => {expr::SaveIn(e)}
1492         None => {
1493             assert!(type_is_zero_size(bcx.ccx(), block_ty))
1494             expr::Ignore
1495         }
1496     };
1497
1498     // This call to trans_block is the place where we bridge between
1499     // translation calls that don't have a return value (trans_crate,
1500     // trans_mod, trans_item, et cetera) and those that do
1501     // (trans_block, trans_expr, et cetera).
1502     bcx = controlflow::trans_block(bcx, body, dest);
1503
1504     match fcx.llreturn.get() {
1505         Some(_) => {
1506             Br(bcx, fcx.return_exit_block());
1507             fcx.pop_custom_cleanup_scope(arg_scope);
1508         }
1509         None => {
1510             // Microoptimization writ large: avoid creating a separate
1511             // llreturn basic block
1512             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1513         }
1514     };
1515
1516     // Put return block after all other blocks.
1517     // This somewhat improves single-stepping experience in debugger.
1518     unsafe {
1519         let llreturn = fcx.llreturn.get();
1520         for &llreturn in llreturn.iter() {
1521             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1522         }
1523     }
1524
1525     // Insert the mandatory first few basic blocks before lltop.
1526     finish_fn(&fcx, bcx);
1527 }
1528
1529 // trans_fn: creates an LLVM function corresponding to a source language
1530 // function.
1531 pub fn trans_fn(ccx: @CrateContext,
1532                 decl: &ast::FnDecl,
1533                 body: &ast::Block,
1534                 llfndecl: ValueRef,
1535                 param_substs: Option<@param_substs>,
1536                 id: ast::NodeId,
1537                 attrs: &[ast::Attribute]) {
1538     let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id));
1539     debug!("trans_fn(param_substs={})", param_substs.repr(ccx.tcx));
1540     let _icx = push_ctxt("trans_fn");
1541     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx, id));
1542     trans_closure(ccx, decl, body, llfndecl,
1543                   param_substs, id, attrs, output_type, |bcx| bcx);
1544 }
1545
1546 pub fn trans_enum_variant(ccx: @CrateContext,
1547                           _enum_id: ast::NodeId,
1548                           variant: &ast::Variant,
1549                           _args: &[ast::VariantArg],
1550                           disr: ty::Disr,
1551                           param_substs: Option<@param_substs>,
1552                           llfndecl: ValueRef) {
1553     let _icx = push_ctxt("trans_enum_variant");
1554
1555     trans_enum_variant_or_tuple_like_struct(
1556         ccx,
1557         variant.node.id,
1558         disr,
1559         param_substs,
1560         llfndecl);
1561 }
1562
1563 pub fn trans_tuple_struct(ccx: @CrateContext,
1564                           _fields: &[ast::StructField],
1565                           ctor_id: ast::NodeId,
1566                           param_substs: Option<@param_substs>,
1567                           llfndecl: ValueRef) {
1568     let _icx = push_ctxt("trans_tuple_struct");
1569
1570     trans_enum_variant_or_tuple_like_struct(
1571         ccx,
1572         ctor_id,
1573         0,
1574         param_substs,
1575         llfndecl);
1576 }
1577
1578 fn trans_enum_variant_or_tuple_like_struct(ccx: @CrateContext,
1579                                            ctor_id: ast::NodeId,
1580                                            disr: ty::Disr,
1581                                            param_substs: Option<@param_substs>,
1582                                            llfndecl: ValueRef) {
1583     let no_substs: &[ty::t] = [];
1584     let ty_param_substs = match param_substs {
1585         Some(ref substs) => {
1586             let v: &[ty::t] = substs.tys;
1587             v
1588         }
1589         None => {
1590             let v: &[ty::t] = no_substs;
1591             v
1592         }
1593     };
1594
1595     let ctor_ty = ty::subst_tps(ccx.tcx,
1596                                 ty_param_substs,
1597                                 None,
1598                                 ty::node_id_to_type(ccx.tcx, ctor_id));
1599
1600     let result_ty = match ty::get(ctor_ty).sty {
1601         ty::ty_bare_fn(ref bft) => bft.sig.output,
1602         _ => ccx.sess.bug(
1603             format!("trans_enum_variant_or_tuple_like_struct: \
1604                   unexpected ctor return type {}",
1605                  ty_to_str(ccx.tcx, ctor_ty)))
1606     };
1607
1608     let arena = TypedArena::new();
1609     let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1610                           param_substs, None, &arena);
1611     init_function(&fcx, false, result_ty, param_substs);
1612
1613     let arg_tys = ty::ty_fn_args(ctor_ty);
1614
1615     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys);
1616
1617     let bcx = fcx.entry_bcx.get().unwrap();
1618
1619     if !type_is_zero_size(fcx.ccx, result_ty) {
1620         let repr = adt::represent_type(ccx, result_ty);
1621         adt::trans_start_init(bcx, repr, fcx.llretptr.get().unwrap(), disr);
1622         for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1623             let lldestptr = adt::trans_field_ptr(bcx,
1624                                                  repr,
1625                                                  fcx.llretptr.get().unwrap(),
1626                                                  disr,
1627                                                  i);
1628             arg_datum.store_to(bcx, lldestptr);
1629         }
1630     }
1631
1632     finish_fn(&fcx, bcx);
1633 }
1634
1635 pub fn trans_enum_def(ccx: @CrateContext, enum_definition: &ast::EnumDef,
1636                       id: ast::NodeId, vi: @~[@ty::VariantInfo],
1637                       i: &mut uint) {
1638     for &variant in enum_definition.variants.iter() {
1639         let disr_val = vi[*i].disr_val;
1640         *i += 1;
1641
1642         match variant.node.kind {
1643             ast::TupleVariantKind(ref args) if args.len() > 0 => {
1644                 let llfn = get_item_val(ccx, variant.node.id);
1645                 trans_enum_variant(ccx, id, variant, args.as_slice(),
1646                                    disr_val, None, llfn);
1647             }
1648             ast::TupleVariantKind(_) => {
1649                 // Nothing to do.
1650             }
1651             ast::StructVariantKind(struct_def) => {
1652                 trans_struct_def(ccx, struct_def);
1653             }
1654         }
1655     }
1656 }
1657
1658 pub struct TransItemVisitor {
1659     ccx: @CrateContext,
1660 }
1661
1662 impl Visitor<()> for TransItemVisitor {
1663     fn visit_item(&mut self, i: &ast::Item, _:()) {
1664         trans_item(self.ccx, i);
1665     }
1666 }
1667
1668 pub fn trans_item(ccx: @CrateContext, item: &ast::Item) {
1669     let _icx = push_ctxt("trans_item");
1670     match item.node {
1671       ast::ItemFn(decl, purity, _abis, ref generics, body) => {
1672         if purity == ast::ExternFn  {
1673             let llfndecl = get_item_val(ccx, item.id);
1674             foreign::trans_rust_fn_with_foreign_abi(
1675                 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1676         } else if !generics.is_type_parameterized() {
1677             let llfn = get_item_val(ccx, item.id);
1678             trans_fn(ccx,
1679                      decl,
1680                      body,
1681                      llfn,
1682                      None,
1683                      item.id,
1684                      item.attrs.as_slice());
1685         } else {
1686             // Be sure to travel more than just one layer deep to catch nested
1687             // items in blocks and such.
1688             let mut v = TransItemVisitor{ ccx: ccx };
1689             v.visit_block(body, ());
1690         }
1691       }
1692       ast::ItemImpl(ref generics, _, _, ref ms) => {
1693         meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1694       }
1695       ast::ItemMod(ref m) => {
1696         trans_mod(ccx, m);
1697       }
1698       ast::ItemEnum(ref enum_definition, ref generics) => {
1699         if !generics.is_type_parameterized() {
1700             let vi = ty::enum_variants(ccx.tcx, local_def(item.id));
1701             let mut i = 0;
1702             trans_enum_def(ccx, enum_definition, item.id, vi, &mut i);
1703         }
1704       }
1705       ast::ItemStatic(_, m, expr) => {
1706           consts::trans_const(ccx, m, item.id);
1707           // Do static_assert checking. It can't really be done much earlier
1708           // because we need to get the value of the bool out of LLVM
1709           if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1710               if m == ast::MutMutable {
1711                   ccx.sess.span_fatal(expr.span,
1712                                       "cannot have static_assert on a mutable \
1713                                        static");
1714               }
1715
1716               let const_values = ccx.const_values.borrow();
1717               let v = const_values.get().get_copy(&item.id);
1718               unsafe {
1719                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1720                       ccx.sess.span_fatal(expr.span, "static assertion failed");
1721                   }
1722               }
1723           }
1724       },
1725       ast::ItemForeignMod(ref foreign_mod) => {
1726         foreign::trans_foreign_mod(ccx, foreign_mod);
1727       }
1728       ast::ItemStruct(struct_def, ref generics) => {
1729         if !generics.is_type_parameterized() {
1730             trans_struct_def(ccx, struct_def);
1731         }
1732       }
1733       ast::ItemTrait(..) => {
1734         // Inside of this trait definition, we won't be actually translating any
1735         // functions, but the trait still needs to be walked. Otherwise default
1736         // methods with items will not get translated and will cause ICE's when
1737         // metadata time comes around.
1738         let mut v = TransItemVisitor{ ccx: ccx };
1739         visit::walk_item(&mut v, item, ());
1740       }
1741       _ => {/* fall through */ }
1742     }
1743 }
1744
1745 pub fn trans_struct_def(ccx: @CrateContext, struct_def: @ast::StructDef) {
1746     // If this is a tuple-like struct, translate the constructor.
1747     match struct_def.ctor_id {
1748         // We only need to translate a constructor if there are fields;
1749         // otherwise this is a unit-like struct.
1750         Some(ctor_id) if struct_def.fields.len() > 0 => {
1751             let llfndecl = get_item_val(ccx, ctor_id);
1752             trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1753                                ctor_id, None, llfndecl);
1754         }
1755         Some(_) | None => {}
1756     }
1757 }
1758
1759 // Translate a module. Doing this amounts to translating the items in the
1760 // module; there ends up being no artifact (aside from linkage names) of
1761 // separate modules in the compiled program.  That's because modules exist
1762 // only as a convenience for humans working with the code, to organize names
1763 // and control visibility.
1764 pub fn trans_mod(ccx: @CrateContext, m: &ast::Mod) {
1765     let _icx = push_ctxt("trans_mod");
1766     for item in m.items.iter() {
1767         trans_item(ccx, *item);
1768     }
1769 }
1770
1771 fn finish_register_fn(ccx: @CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1772                       llfn: ValueRef) {
1773     {
1774         let mut item_symbols = ccx.item_symbols.borrow_mut();
1775         item_symbols.get().insert(node_id, sym);
1776     }
1777
1778     {
1779         let reachable = ccx.reachable.borrow();
1780         if !reachable.get().contains(&node_id) {
1781             lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1782         }
1783     }
1784
1785     if is_entry_fn(&ccx.sess, node_id) && !ccx.sess.building_library.get() {
1786         create_entry_wrapper(ccx, sp, llfn);
1787     }
1788 }
1789
1790 fn register_fn(ccx: @CrateContext,
1791                sp: Span,
1792                sym: ~str,
1793                node_id: ast::NodeId,
1794                node_type: ty::t)
1795                -> ValueRef {
1796     let f = match ty::get(node_type).sty {
1797         ty::ty_bare_fn(ref f) => {
1798             assert!(f.abis.is_rust() || f.abis.is_intrinsic());
1799             f
1800         }
1801         _ => fail!("expected bare rust fn or an intrinsic")
1802     };
1803
1804     let llfn = decl_rust_fn(ccx, false, f.sig.inputs, f.sig.output, sym);
1805     finish_register_fn(ccx, sp, sym, node_id, llfn);
1806     llfn
1807 }
1808
1809 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1810 pub fn register_fn_llvmty(ccx: @CrateContext,
1811                           sp: Span,
1812                           sym: ~str,
1813                           node_id: ast::NodeId,
1814                           cc: lib::llvm::CallConv,
1815                           fn_ty: Type,
1816                           output: ty::t) -> ValueRef {
1817     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1818
1819     let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1820     finish_register_fn(ccx, sp, sym, node_id, llfn);
1821     llfn
1822 }
1823
1824 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1825     match sess.entry_fn.get() {
1826         Some((entry_id, _)) => node_id == entry_id,
1827         None => false
1828     }
1829 }
1830
1831 // Create a _rust_main(args: ~[str]) function which will be called from the
1832 // runtime rust_start function
1833 pub fn create_entry_wrapper(ccx: @CrateContext,
1834                            _sp: Span,
1835                            main_llfn: ValueRef) {
1836     let et = ccx.sess.entry_type.get().unwrap();
1837     match et {
1838         session::EntryMain => {
1839             create_entry_fn(ccx, main_llfn, true);
1840         }
1841         session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1842         session::EntryNone => {}    // Do nothing.
1843     }
1844
1845     fn create_entry_fn(ccx: @CrateContext,
1846                        rust_main: ValueRef,
1847                        use_start_lang_item: bool) {
1848         let llfty = Type::func([ccx.int_type, Type::i8().ptr_to().ptr_to()],
1849                                &ccx.int_type);
1850
1851         let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1852         let llbb = "top".with_c_str(|buf| {
1853             unsafe {
1854                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1855             }
1856         });
1857         let bld = ccx.builder.b;
1858         unsafe {
1859             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1860
1861             let (start_fn, args) = if use_start_lang_item {
1862                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1863                     Ok(id) => id,
1864                     Err(s) => { ccx.tcx.sess.fatal(s); }
1865                 };
1866                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1867                     get_item_val(ccx, start_def_id.node)
1868                 } else {
1869                     let start_fn_type = csearch::get_type(ccx.tcx,
1870                                                           start_def_id).ty;
1871                     trans_external_path(ccx, start_def_id, start_fn_type)
1872                 };
1873
1874                 let args = {
1875                     let opaque_rust_main = "rust_main".with_c_str(|buf| {
1876                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p().to_ref(), buf)
1877                     });
1878
1879                     ~[
1880                         opaque_rust_main,
1881                         llvm::LLVMGetParam(llfn, 0),
1882                         llvm::LLVMGetParam(llfn, 1)
1883                      ]
1884                 };
1885                 (start_fn, args)
1886             } else {
1887                 debug!("using user-defined start fn");
1888                 let args = ~[
1889                     llvm::LLVMGetParam(llfn, 0 as c_uint),
1890                     llvm::LLVMGetParam(llfn, 1 as c_uint)
1891                 ];
1892
1893                 (rust_main, args)
1894             };
1895
1896             let result = llvm::LLVMBuildCall(bld, start_fn,
1897                                              args.as_ptr(), args.len() as c_uint,
1898                                              noname());
1899
1900             llvm::LLVMBuildRet(bld, result);
1901         }
1902     }
1903 }
1904
1905 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1906                  ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1907     match attr::first_attr_value_str_by_name(attrs, "export_name") {
1908         // Use provided name
1909         Some(name) => name.get().to_owned(),
1910
1911         _ => ccx.tcx.map.with_path(id, |mut path| {
1912             if attr::contains_name(attrs, "no_mangle") {
1913                 // Don't mangle
1914                 path.last().unwrap().to_str()
1915             } else {
1916                 // Usual name mangling
1917                 mangle_exported_name(ccx, path, ty, id)
1918             }
1919         })
1920     }
1921 }
1922
1923 pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
1924     debug!("get_item_val(id=`{:?}`)", id);
1925
1926     let val = {
1927         let item_vals = ccx.item_vals.borrow();
1928         item_vals.get().find_copy(&id)
1929     };
1930
1931     match val {
1932         Some(v) => v,
1933         None => {
1934             let mut foreign = false;
1935             let item = ccx.tcx.map.get(id);
1936             let val = match item {
1937                 ast_map::NodeItem(i) => {
1938                     let ty = ty::node_id_to_type(ccx.tcx, i.id);
1939                     let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1940
1941                     let v = match i.node {
1942                         ast::ItemStatic(_, _, expr) => {
1943                             // If this static came from an external crate, then
1944                             // we need to get the symbol from csearch instead of
1945                             // using the current crate's name/version
1946                             // information in the hash of the symbol
1947                             debug!("making {}", sym);
1948                             let (sym, is_local) = {
1949                                 let external_srcs = ccx.external_srcs
1950                                                        .borrow();
1951                                 match external_srcs.get().find(&i.id) {
1952                                     Some(&did) => {
1953                                         debug!("but found in other crate...");
1954                                         (csearch::get_symbol(ccx.sess.cstore,
1955                                                              did), false)
1956                                     }
1957                                     None => (sym, true)
1958                                 }
1959                             };
1960
1961                             // We need the translated value here, because for enums the
1962                             // LLVM type is not fully determined by the Rust type.
1963                             let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1964                             {
1965                                 let mut const_values = ccx.const_values
1966                                                           .borrow_mut();
1967                                 const_values.get().insert(id, v);
1968                             }
1969                             let mut inlineable = inlineable;
1970
1971                             unsafe {
1972                                 let llty = llvm::LLVMTypeOf(v);
1973                                 let g = sym.with_c_str(|buf| {
1974                                     llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1975                                 });
1976
1977                                 {
1978                                     let reachable = ccx.reachable.borrow();
1979                                     if !reachable.get().contains(&id) {
1980                                         lib::llvm::SetLinkage(
1981                                             g,
1982                                             lib::llvm::InternalLinkage);
1983                                     }
1984                                 }
1985
1986                                 // Apply the `unnamed_addr` attribute if
1987                                 // requested
1988                                 if attr::contains_name(i.attrs.as_slice(),
1989                                                        "address_insignificant"){
1990                                     {
1991                                         let reachable =
1992                                             ccx.reachable.borrow();
1993                                         if reachable.get().contains(&id) {
1994                                             ccx.sess.span_bug(i.span,
1995                                                 "insignificant static is \
1996                                                  reachable");
1997                                         }
1998                                     }
1999                                     lib::llvm::SetUnnamedAddr(g, true);
2000
2001                                     // This is a curious case where we must make
2002                                     // all of these statics inlineable. If a
2003                                     // global is tagged as
2004                                     // address_insignificant, then LLVM won't
2005                                     // coalesce globals unless they have an
2006                                     // internal linkage type. This means that
2007                                     // external crates cannot use this global.
2008                                     // This is a problem for things like inner
2009                                     // statics in generic functions, because the
2010                                     // function will be inlined into another
2011                                     // crate and then attempt to link to the
2012                                     // static in the original crate, only to
2013                                     // find that it's not there. On the other
2014                                     // side of inlininig, the crates knows to
2015                                     // not declare this static as
2016                                     // available_externally (because it isn't)
2017                                     inlineable = true;
2018                                 }
2019
2020                                 if attr::contains_name(i.attrs.as_slice(),
2021                                                        "thread_local") {
2022                                     lib::llvm::set_thread_local(g, true);
2023                                 }
2024
2025                                 if !inlineable {
2026                                     debug!("{} not inlined", sym);
2027                                     let mut non_inlineable_statics =
2028                                         ccx.non_inlineable_statics
2029                                            .borrow_mut();
2030                                     non_inlineable_statics.get().insert(id);
2031                                 }
2032
2033                                 let mut item_symbols = ccx.item_symbols
2034                                                           .borrow_mut();
2035                                 item_symbols.get().insert(i.id, sym);
2036                                 g
2037                             }
2038                         }
2039
2040                         ast::ItemFn(_, purity, _, _, _) => {
2041                             let llfn = if purity != ast::ExternFn {
2042                                 register_fn(ccx, i.span, sym, i.id, ty)
2043                             } else {
2044                                 foreign::register_rust_fn_with_foreign_abi(ccx,
2045                                                                            i.span,
2046                                                                            sym,
2047                                                                            i.id)
2048                             };
2049                             set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
2050                             llfn
2051                         }
2052
2053                         _ => fail!("get_item_val: weird result in table")
2054                     };
2055
2056                     match attr::first_attr_value_str_by_name(i.attrs
2057                                                               .as_slice(),
2058                                                              "link_section") {
2059                         Some(sect) => unsafe {
2060                             sect.get().with_c_str(|buf| {
2061                                 llvm::LLVMSetSection(v, buf);
2062                             })
2063                         },
2064                         None => ()
2065                     }
2066
2067                     v
2068                 }
2069
2070                 ast_map::NodeTraitMethod(trait_method) => {
2071                     debug!("get_item_val(): processing a NodeTraitMethod");
2072                     match *trait_method {
2073                         ast::Required(_) => {
2074                             ccx.sess.bug("unexpected variant: required trait method in \
2075                                          get_item_val()");
2076                         }
2077                         ast::Provided(m) => {
2078                             register_method(ccx, id, m)
2079                         }
2080                     }
2081                 }
2082
2083                 ast_map::NodeMethod(m) => {
2084                     register_method(ccx, id, m)
2085                 }
2086
2087                 ast_map::NodeForeignItem(ni) => {
2088                     let ty = ty::node_id_to_type(ccx.tcx, ni.id);
2089                     foreign = true;
2090
2091                     match ni.node {
2092                         ast::ForeignItemFn(..) => {
2093                             let abis = ccx.tcx.map.get_foreign_abis(id);
2094                             foreign::register_foreign_item_fn(ccx, abis, ni)
2095                         }
2096                         ast::ForeignItemStatic(..) => {
2097                             // Treat the crate map static specially in order to
2098                             // a weak-linkage-like functionality where it's
2099                             // dynamically resolved at runtime. If we're
2100                             // building a library, then we declare the static
2101                             // with weak linkage, but if we're building a
2102                             // library then we've already declared the crate map
2103                             // so use that instead.
2104                             if attr::contains_name(ni.attrs.as_slice(),
2105                                                    "crate_map") {
2106                                 if ccx.sess.building_library.get() {
2107                                     let s = "_rust_crate_map_toplevel";
2108                                     let g = unsafe {
2109                                         s.with_c_str(|buf| {
2110                                             let ty = type_of(ccx, ty);
2111                                             llvm::LLVMAddGlobal(ccx.llmod,
2112                                                                 ty.to_ref(),
2113                                                                 buf)
2114                                         })
2115                                     };
2116                                     lib::llvm::SetLinkage(g,
2117                                         lib::llvm::ExternalWeakLinkage);
2118                                     g
2119                                 } else {
2120                                     ccx.crate_map
2121                                 }
2122                             } else {
2123                                 let ident = foreign::link_name(ni);
2124                                 unsafe {
2125                                     ident.get().with_c_str(|buf| {
2126                                         let ty = type_of(ccx, ty);
2127                                         llvm::LLVMAddGlobal(ccx.llmod,
2128                                                             ty.to_ref(), buf)
2129                                     })
2130                                 }
2131                             }
2132                         }
2133                     }
2134                 }
2135
2136                 ast_map::NodeVariant(ref v) => {
2137                     let llfn;
2138                     match v.node.kind {
2139                         ast::TupleVariantKind(ref args) => {
2140                             assert!(args.len() != 0u);
2141                             let ty = ty::node_id_to_type(ccx.tcx, id);
2142                             let parent = ccx.tcx.map.get_parent(id);
2143                             let enm = ccx.tcx.map.expect_item(parent);
2144                             let sym = exported_name(ccx,
2145                                                     id,
2146                                                     ty,
2147                                                     enm.attrs.as_slice());
2148
2149                             llfn = match enm.node {
2150                                 ast::ItemEnum(_, _) => {
2151                                     register_fn(ccx, (*v).span, sym, id, ty)
2152                                 }
2153                                 _ => fail!("NodeVariant, shouldn't happen")
2154                             };
2155                         }
2156                         ast::StructVariantKind(_) => {
2157                             fail!("struct variant kind unexpected in get_item_val")
2158                         }
2159                     }
2160                     set_inline_hint(llfn);
2161                     llfn
2162                 }
2163
2164                 ast_map::NodeStructCtor(struct_def) => {
2165                     // Only register the constructor if this is a tuple-like struct.
2166                     match struct_def.ctor_id {
2167                         None => {
2168                             ccx.tcx.sess.bug("attempt to register a constructor of \
2169                                               a non-tuple-like struct")
2170                         }
2171                         Some(ctor_id) => {
2172                             let parent = ccx.tcx.map.get_parent(id);
2173                             let struct_item = ccx.tcx.map.expect_item(parent);
2174                             let ty = ty::node_id_to_type(ccx.tcx, ctor_id);
2175                             let sym = exported_name(ccx,
2176                                                     id,
2177                                                     ty,
2178                                                     struct_item.attrs
2179                                                                .as_slice());
2180                             let llfn = register_fn(ccx, struct_item.span,
2181                                                    sym, ctor_id, ty);
2182                             set_inline_hint(llfn);
2183                             llfn
2184                         }
2185                     }
2186                 }
2187
2188                 ref variant => {
2189                     ccx.sess.bug(format!("get_item_val(): unexpected variant: {:?}",
2190                                  variant))
2191                 }
2192             };
2193
2194             // foreign items (extern fns and extern statics) don't have internal
2195             // linkage b/c that doesn't quite make sense. Otherwise items can
2196             // have internal linkage if they're not reachable.
2197             {
2198                 let reachable = ccx.reachable.borrow();
2199                 if !foreign && !reachable.get().contains(&id) {
2200                     lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2201                 }
2202             }
2203
2204             let mut item_vals = ccx.item_vals.borrow_mut();
2205             item_vals.get().insert(id, val);
2206             val
2207         }
2208     }
2209 }
2210
2211 fn register_method(ccx: @CrateContext, id: ast::NodeId,
2212                    m: &ast::Method) -> ValueRef {
2213     let mty = ty::node_id_to_type(ccx.tcx, id);
2214
2215     let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2216
2217     let llfn = register_fn(ccx, m.span, sym, id, mty);
2218     set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2219     llfn
2220 }
2221
2222 pub fn vp2i(cx: &Block, v: ValueRef) -> ValueRef {
2223     let ccx = cx.ccx();
2224     return PtrToInt(cx, v, ccx.int_type);
2225 }
2226
2227 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2228     unsafe {
2229         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2230     }
2231 }
2232
2233 macro_rules! ifn (
2234     ($intrinsics:ident, $name:expr, $args:expr, $ret:expr) => ({
2235         let name = $name;
2236         // HACK(eddyb) dummy output type, shouln't affect anything.
2237         let f = decl_cdecl_fn(llmod, name, Type::func($args, &$ret), ty::mk_nil());
2238         $intrinsics.insert(name, f);
2239     })
2240 )
2241
2242 pub fn declare_intrinsics(llmod: ModuleRef) -> HashMap<&'static str, ValueRef> {
2243     let i8p = Type::i8p();
2244     let mut intrinsics = HashMap::new();
2245
2246     ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i32",
2247          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2248     ifn!(intrinsics, "llvm.memcpy.p0i8.p0i8.i64",
2249          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2250     ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i32",
2251          [i8p, i8p, Type::i32(), Type::i32(), Type::i1()], Type::void());
2252     ifn!(intrinsics, "llvm.memmove.p0i8.p0i8.i64",
2253          [i8p, i8p, Type::i64(), Type::i32(), Type::i1()], Type::void());
2254     ifn!(intrinsics, "llvm.memset.p0i8.i32",
2255          [i8p, Type::i8(), Type::i32(), Type::i32(), Type::i1()], Type::void());
2256     ifn!(intrinsics, "llvm.memset.p0i8.i64",
2257          [i8p, Type::i8(), Type::i64(), Type::i32(), Type::i1()], Type::void());
2258
2259     ifn!(intrinsics, "llvm.trap", [], Type::void());
2260     ifn!(intrinsics, "llvm.debugtrap", [], Type::void());
2261     ifn!(intrinsics, "llvm.frameaddress", [Type::i32()], i8p);
2262
2263     ifn!(intrinsics, "llvm.powi.f32", [Type::f32(), Type::i32()], Type::f32());
2264     ifn!(intrinsics, "llvm.powi.f64", [Type::f64(), Type::i32()], Type::f64());
2265     ifn!(intrinsics, "llvm.pow.f32",  [Type::f32(), Type::f32()], Type::f32());
2266     ifn!(intrinsics, "llvm.pow.f64",  [Type::f64(), Type::f64()], Type::f64());
2267
2268     ifn!(intrinsics, "llvm.sqrt.f32", [Type::f32()], Type::f32());
2269     ifn!(intrinsics, "llvm.sqrt.f64", [Type::f64()], Type::f64());
2270     ifn!(intrinsics, "llvm.sin.f32",  [Type::f32()], Type::f32());
2271     ifn!(intrinsics, "llvm.sin.f64",  [Type::f64()], Type::f64());
2272     ifn!(intrinsics, "llvm.cos.f32",  [Type::f32()], Type::f32());
2273     ifn!(intrinsics, "llvm.cos.f64",  [Type::f64()], Type::f64());
2274     ifn!(intrinsics, "llvm.exp.f32",  [Type::f32()], Type::f32());
2275     ifn!(intrinsics, "llvm.exp.f64",  [Type::f64()], Type::f64());
2276     ifn!(intrinsics, "llvm.exp2.f32", [Type::f32()], Type::f32());
2277     ifn!(intrinsics, "llvm.exp2.f64", [Type::f64()], Type::f64());
2278     ifn!(intrinsics, "llvm.log.f32",  [Type::f32()], Type::f32());
2279     ifn!(intrinsics, "llvm.log.f64",  [Type::f64()], Type::f64());
2280     ifn!(intrinsics, "llvm.log10.f32",[Type::f32()], Type::f32());
2281     ifn!(intrinsics, "llvm.log10.f64",[Type::f64()], Type::f64());
2282     ifn!(intrinsics, "llvm.log2.f32", [Type::f32()], Type::f32());
2283     ifn!(intrinsics, "llvm.log2.f64", [Type::f64()], Type::f64());
2284
2285     ifn!(intrinsics, "llvm.fma.f32",  [Type::f32(), Type::f32(), Type::f32()], Type::f32());
2286     ifn!(intrinsics, "llvm.fma.f64",  [Type::f64(), Type::f64(), Type::f64()], Type::f64());
2287
2288     ifn!(intrinsics, "llvm.fabs.f32", [Type::f32()], Type::f32());
2289     ifn!(intrinsics, "llvm.fabs.f64", [Type::f64()], Type::f64());
2290
2291     ifn!(intrinsics, "llvm.floor.f32",[Type::f32()], Type::f32());
2292     ifn!(intrinsics, "llvm.floor.f64",[Type::f64()], Type::f64());
2293     ifn!(intrinsics, "llvm.ceil.f32", [Type::f32()], Type::f32());
2294     ifn!(intrinsics, "llvm.ceil.f64", [Type::f64()], Type::f64());
2295     ifn!(intrinsics, "llvm.trunc.f32",[Type::f32()], Type::f32());
2296     ifn!(intrinsics, "llvm.trunc.f64",[Type::f64()], Type::f64());
2297
2298     ifn!(intrinsics, "llvm.rint.f32", [Type::f32()], Type::f32());
2299     ifn!(intrinsics, "llvm.rint.f64", [Type::f64()], Type::f64());
2300     ifn!(intrinsics, "llvm.nearbyint.f32", [Type::f32()], Type::f32());
2301     ifn!(intrinsics, "llvm.nearbyint.f64", [Type::f64()], Type::f64());
2302
2303     ifn!(intrinsics, "llvm.ctpop.i8", [Type::i8()], Type::i8());
2304     ifn!(intrinsics, "llvm.ctpop.i16",[Type::i16()], Type::i16());
2305     ifn!(intrinsics, "llvm.ctpop.i32",[Type::i32()], Type::i32());
2306     ifn!(intrinsics, "llvm.ctpop.i64",[Type::i64()], Type::i64());
2307
2308     ifn!(intrinsics, "llvm.ctlz.i8",  [Type::i8() , Type::i1()], Type::i8());
2309     ifn!(intrinsics, "llvm.ctlz.i16", [Type::i16(), Type::i1()], Type::i16());
2310     ifn!(intrinsics, "llvm.ctlz.i32", [Type::i32(), Type::i1()], Type::i32());
2311     ifn!(intrinsics, "llvm.ctlz.i64", [Type::i64(), Type::i1()], Type::i64());
2312
2313     ifn!(intrinsics, "llvm.cttz.i8",  [Type::i8() , Type::i1()], Type::i8());
2314     ifn!(intrinsics, "llvm.cttz.i16", [Type::i16(), Type::i1()], Type::i16());
2315     ifn!(intrinsics, "llvm.cttz.i32", [Type::i32(), Type::i1()], Type::i32());
2316     ifn!(intrinsics, "llvm.cttz.i64", [Type::i64(), Type::i1()], Type::i64());
2317
2318     ifn!(intrinsics, "llvm.bswap.i16",[Type::i16()], Type::i16());
2319     ifn!(intrinsics, "llvm.bswap.i32",[Type::i32()], Type::i32());
2320     ifn!(intrinsics, "llvm.bswap.i64",[Type::i64()], Type::i64());
2321
2322     ifn!(intrinsics, "llvm.sadd.with.overflow.i8",
2323         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2324     ifn!(intrinsics, "llvm.sadd.with.overflow.i16",
2325         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2326     ifn!(intrinsics, "llvm.sadd.with.overflow.i32",
2327         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2328     ifn!(intrinsics, "llvm.sadd.with.overflow.i64",
2329         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2330
2331     ifn!(intrinsics, "llvm.uadd.with.overflow.i8",
2332         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2333     ifn!(intrinsics, "llvm.uadd.with.overflow.i16",
2334         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2335     ifn!(intrinsics, "llvm.uadd.with.overflow.i32",
2336         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2337     ifn!(intrinsics, "llvm.uadd.with.overflow.i64",
2338         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2339
2340     ifn!(intrinsics, "llvm.ssub.with.overflow.i8",
2341         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2342     ifn!(intrinsics, "llvm.ssub.with.overflow.i16",
2343         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2344     ifn!(intrinsics, "llvm.ssub.with.overflow.i32",
2345         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2346     ifn!(intrinsics, "llvm.ssub.with.overflow.i64",
2347         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2348
2349     ifn!(intrinsics, "llvm.usub.with.overflow.i8",
2350         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2351     ifn!(intrinsics, "llvm.usub.with.overflow.i16",
2352         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2353     ifn!(intrinsics, "llvm.usub.with.overflow.i32",
2354         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2355     ifn!(intrinsics, "llvm.usub.with.overflow.i64",
2356         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2357
2358     ifn!(intrinsics, "llvm.smul.with.overflow.i8",
2359         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2360     ifn!(intrinsics, "llvm.smul.with.overflow.i16",
2361         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2362     ifn!(intrinsics, "llvm.smul.with.overflow.i32",
2363         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2364     ifn!(intrinsics, "llvm.smul.with.overflow.i64",
2365         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2366
2367     ifn!(intrinsics, "llvm.umul.with.overflow.i8",
2368         [Type::i8(), Type::i8()], Type::struct_([Type::i8(), Type::i1()], false));
2369     ifn!(intrinsics, "llvm.umul.with.overflow.i16",
2370         [Type::i16(), Type::i16()], Type::struct_([Type::i16(), Type::i1()], false));
2371     ifn!(intrinsics, "llvm.umul.with.overflow.i32",
2372         [Type::i32(), Type::i32()], Type::struct_([Type::i32(), Type::i1()], false));
2373     ifn!(intrinsics, "llvm.umul.with.overflow.i64",
2374         [Type::i64(), Type::i64()], Type::struct_([Type::i64(), Type::i1()], false));
2375
2376     ifn!(intrinsics, "llvm.expect.i1", [Type::i1(), Type::i1()], Type::i1());
2377
2378     // Some intrinsics were introduced in later versions of LLVM, but they have
2379     // fallbacks in libc or libm and such. Currently, all of these intrinsics
2380     // were introduced in LLVM 3.4, so we case on that.
2381     macro_rules! compatible_ifn (
2382         ($intrinsics:ident, $name:expr, $cname:expr, $args:expr, $ret:expr) => ({
2383             let name = $name;
2384             if unsafe { llvm::LLVMVersionMinor() >= 4 } {
2385                 ifn!($intrinsics, $name, $args, $ret);
2386             } else {
2387                 let f = decl_cdecl_fn(llmod, $cname,
2388                                       Type::func($args, &$ret),
2389                                       ty::mk_nil());
2390                 $intrinsics.insert(name, f);
2391             }
2392         })
2393     )
2394
2395     compatible_ifn!(intrinsics, "llvm.copysign.f32", "copysignf",
2396                     [Type::f32(), Type::f32()], Type::f32());
2397     compatible_ifn!(intrinsics, "llvm.copysign.f64", "copysign",
2398                     [Type::f64(), Type::f64()], Type::f64());
2399     compatible_ifn!(intrinsics, "llvm.round.f32", "roundf",
2400                     [Type::f32()], Type::f32());
2401     compatible_ifn!(intrinsics, "llvm.round.f64", "round",
2402                     [Type::f64()], Type::f64());
2403
2404     return intrinsics;
2405 }
2406
2407 pub fn declare_dbg_intrinsics(llmod: ModuleRef, intrinsics: &mut HashMap<&'static str, ValueRef>) {
2408     ifn!(intrinsics, "llvm.dbg.declare", [Type::metadata(), Type::metadata()], Type::void());
2409     ifn!(intrinsics,
2410          "llvm.dbg.value",   [Type::metadata(), Type::i64(), Type::metadata()], Type::void());
2411 }
2412
2413 pub fn trap(bcx: &Block) {
2414     match bcx.ccx().intrinsics.find_equiv(& &"llvm.trap") {
2415       Some(&x) => { Call(bcx, x, [], []); },
2416       _ => bcx.sess().bug("unbound llvm.trap in trap")
2417     }
2418 }
2419
2420 pub fn decl_gc_metadata(ccx: &CrateContext, llmod_id: &str) {
2421     if !ccx.sess.opts.gc || !ccx.uses_gc {
2422         return;
2423     }
2424
2425     let gc_metadata_name = ~"_gc_module_metadata_" + llmod_id;
2426     let gc_metadata = gc_metadata_name.with_c_str(|buf| {
2427         unsafe {
2428             llvm::LLVMAddGlobal(ccx.llmod, Type::i32().to_ref(), buf)
2429         }
2430     });
2431     unsafe {
2432         llvm::LLVMSetGlobalConstant(gc_metadata, True);
2433         lib::llvm::SetLinkage(gc_metadata, lib::llvm::ExternalLinkage);
2434
2435         let mut module_data = ccx.module_data.borrow_mut();
2436         module_data.get().insert(~"_gc_module_metadata", gc_metadata);
2437     }
2438 }
2439
2440 pub fn create_module_map(ccx: &CrateContext) -> (ValueRef, uint) {
2441     let str_slice_type = Type::struct_([Type::i8p(), ccx.int_type], false);
2442     let elttype = Type::struct_([str_slice_type, ccx.int_type], false);
2443     let maptype = {
2444         let module_data = ccx.module_data.borrow();
2445         Type::array(&elttype, module_data.get().len() as u64)
2446     };
2447     let map = "_rust_mod_map".with_c_str(|buf| {
2448         unsafe {
2449             llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2450         }
2451     });
2452     lib::llvm::SetLinkage(map, lib::llvm::InternalLinkage);
2453     let mut elts: ~[ValueRef] = ~[];
2454
2455     // This is not ideal, but the borrow checker doesn't
2456     // like the multiple borrows. At least, it doesn't
2457     // like them on the current snapshot. (2013-06-14)
2458     let keys = {
2459         let mut keys = ~[];
2460         let module_data = ccx.module_data.borrow();
2461         for (k, _) in module_data.get().iter() {
2462             keys.push(k.clone());
2463         }
2464         keys
2465     };
2466
2467     for key in keys.iter() {
2468         let llstrval = C_str_slice(ccx, token::intern_and_get_ident(*key));
2469         let module_data = ccx.module_data.borrow();
2470         let val = *module_data.get().find_equiv(key).unwrap();
2471         let v_ptr = p2i(ccx, val);
2472         let elt = C_struct([
2473             llstrval,
2474             v_ptr
2475         ], false);
2476         elts.push(elt);
2477     }
2478     unsafe {
2479         llvm::LLVMSetInitializer(map, C_array(elttype, elts));
2480     }
2481     return (map, keys.len())
2482 }
2483
2484 pub fn symname(name: &str, hash: &str, vers: &str) -> ~str {
2485     let path = [PathName(token::intern(name))];
2486     link::exported_name(ast_map::Values(path.iter()).chain(None), hash, vers)
2487 }
2488
2489 pub fn decl_crate_map(sess: session::Session, mapmeta: LinkMeta,
2490                       llmod: ModuleRef) -> (~str, ValueRef) {
2491     let targ_cfg = sess.targ_cfg;
2492     let int_type = Type::int(targ_cfg.arch);
2493     let mut n_subcrates = 1;
2494     let cstore = sess.cstore;
2495     while cstore.have_crate_data(n_subcrates) { n_subcrates += 1; }
2496     let is_top = !sess.building_library.get() || sess.opts.cg.gen_crate_map;
2497     let sym_name = if is_top {
2498         ~"_rust_crate_map_toplevel"
2499     } else {
2500         symname("_rust_crate_map_" + mapmeta.crateid.name,
2501                 mapmeta.crate_hash.as_str(),
2502                 mapmeta.crateid.version_or_default())
2503     };
2504
2505     let slicetype = Type::struct_([int_type, int_type], false);
2506     let maptype = Type::struct_([
2507         Type::i32(),        // version
2508         slicetype,          // child modules
2509         slicetype,          // sub crate-maps
2510         int_type.ptr_to(),  // event loop factory
2511     ], false);
2512     let map = sym_name.with_c_str(|buf| {
2513         unsafe {
2514             llvm::LLVMAddGlobal(llmod, maptype.to_ref(), buf)
2515         }
2516     });
2517     lib::llvm::SetLinkage(map, lib::llvm::ExternalLinkage);
2518
2519     // On windows we'd like to export the toplevel cratemap
2520     // such that we can find it from libstd.
2521     if targ_cfg.os == OsWin32 && is_top {
2522         unsafe { llvm::LLVMRustSetDLLExportStorageClass(map) }
2523     }
2524
2525     return (sym_name, map);
2526 }
2527
2528 pub fn fill_crate_map(ccx: @CrateContext, map: ValueRef) {
2529     let mut subcrates: ~[ValueRef] = ~[];
2530     let mut i = 1;
2531     let cstore = ccx.sess.cstore;
2532     while cstore.have_crate_data(i) {
2533         let cdata = cstore.get_crate_data(i);
2534         let nm = symname(format!("_rust_crate_map_{}", cdata.name),
2535                          cstore.get_crate_hash(i).as_str(),
2536                          cstore.get_crate_id(i).version_or_default());
2537         let cr = nm.with_c_str(|buf| {
2538             unsafe {
2539                 llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2540             }
2541         });
2542         subcrates.push(p2i(ccx, cr));
2543         i += 1;
2544     }
2545     let event_loop_factory = match ccx.tcx.lang_items.event_loop_factory() {
2546         Some(did) => unsafe {
2547             if is_local(did) {
2548                 llvm::LLVMConstPointerCast(get_item_val(ccx, did.node),
2549                                            ccx.int_type.ptr_to().to_ref())
2550             } else {
2551                 let name = csearch::get_symbol(ccx.sess.cstore, did);
2552                 let global = name.with_c_str(|buf| {
2553                     llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type.to_ref(), buf)
2554                 });
2555                 global
2556             }
2557         },
2558         None => C_null(ccx.int_type.ptr_to())
2559     };
2560     unsafe {
2561         let maptype = Type::array(&ccx.int_type, subcrates.len() as u64);
2562         let vec_elements = "_crate_map_child_vectors".with_c_str(|buf| {
2563             llvm::LLVMAddGlobal(ccx.llmod, maptype.to_ref(), buf)
2564         });
2565         lib::llvm::SetLinkage(vec_elements, lib::llvm::InternalLinkage);
2566
2567         llvm::LLVMSetInitializer(vec_elements, C_array(ccx.int_type, subcrates));
2568         let (mod_map, mod_count) = create_module_map(ccx);
2569
2570         llvm::LLVMSetInitializer(map, C_struct(
2571             [C_i32(2),
2572              C_struct([
2573                 p2i(ccx, mod_map),
2574                 C_uint(ccx, mod_count)
2575              ], false),
2576              C_struct([
2577                 p2i(ccx, vec_elements),
2578                 C_uint(ccx, subcrates.len())
2579              ], false),
2580             event_loop_factory,
2581         ], false));
2582     }
2583 }
2584
2585 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2586     -> encoder::EncodeParams<'r> {
2587
2588         let diag = cx.sess.diagnostic();
2589         let item_symbols = &cx.item_symbols;
2590         let link_meta = &cx.link_meta;
2591         encoder::EncodeParams {
2592             diag: diag,
2593             tcx: cx.tcx,
2594             reexports2: cx.exp_map2,
2595             item_symbols: item_symbols,
2596             non_inlineable_statics: &cx.non_inlineable_statics,
2597             link_meta: link_meta,
2598             cstore: cx.sess.cstore,
2599             encode_inlined_item: ie,
2600         }
2601 }
2602
2603 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> ~[u8] {
2604     use flate;
2605
2606     if !cx.sess.building_library.get() {
2607         return ~[]
2608     }
2609
2610     let encode_inlined_item: encoder::EncodeInlinedItem =
2611         |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii, cx.maps);
2612
2613     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2614     let metadata = encoder::encode_metadata(encode_parms, krate);
2615     let compressed = encoder::metadata_encoding_version +
2616                         flate::deflate_bytes(metadata).as_slice();
2617     let llmeta = C_bytes(compressed);
2618     let llconst = C_struct([llmeta], false);
2619     let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2620                        cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2621     let llglobal = name.with_c_str(|buf| {
2622         unsafe {
2623             llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2624         }
2625     });
2626     unsafe {
2627         llvm::LLVMSetInitializer(llglobal, llconst);
2628         cx.sess.targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2629             llvm::LLVMSetSection(llglobal, buf)
2630         });
2631     }
2632     return metadata;
2633 }
2634
2635 pub fn trans_crate(sess: session::Session,
2636                    krate: ast::Crate,
2637                    analysis: &CrateAnalysis,
2638                    output: &OutputFilenames) -> CrateTranslation {
2639     // Before we touch LLVM, make sure that multithreading is enabled.
2640     unsafe {
2641         use sync::one::{Once, ONCE_INIT};
2642         static mut INIT: Once = ONCE_INIT;
2643         static mut POISONED: bool = false;
2644         INIT.doit(|| {
2645             if llvm::LLVMStartMultithreaded() != 1 {
2646                 // use an extra bool to make sure that all future usage of LLVM
2647                 // cannot proceed despite the Once not running more than once.
2648                 POISONED = true;
2649             }
2650         });
2651
2652         if POISONED {
2653             sess.bug("couldn't enable multi-threaded LLVM");
2654         }
2655     }
2656
2657     let link_meta = link::build_link_meta(&krate, output);
2658
2659     // Append ".rs" to crate name as LLVM module identifier.
2660     //
2661     // LLVM code generator emits a ".file filename" directive
2662     // for ELF backends. Value of the "filename" is set as the
2663     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2664     // crashes if the module identifer is same as other symbols
2665     // such as a function name in the module.
2666     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2667     let llmod_id = link_meta.crateid.name + ".rs";
2668
2669     let ccx = @CrateContext::new(sess,
2670                                  llmod_id,
2671                                  analysis.ty_cx,
2672                                  analysis.exp_map2,
2673                                  analysis.maps,
2674                                  Sha256::new(),
2675                                  link_meta,
2676                                  analysis.reachable);
2677     {
2678         let _icx = push_ctxt("text");
2679         trans_mod(ccx, &krate.module);
2680     }
2681
2682     decl_gc_metadata(ccx, llmod_id);
2683     fill_crate_map(ccx, ccx.crate_map);
2684
2685     // win32: wart with exporting crate_map symbol
2686     // We set the crate map (_rust_crate_map_toplevel) to use dll_export
2687     // linkage but that ends up causing the linker to look for a
2688     // __rust_crate_map_toplevel symbol (extra underscore) which it will
2689     // subsequently fail to find. So to mitigate that we just introduce
2690     // an alias from the symbol it expects to the one that actually exists.
2691     if ccx.sess.targ_cfg.os == OsWin32 && !ccx.sess.building_library.get() {
2692
2693         let maptype = val_ty(ccx.crate_map).to_ref();
2694
2695         "__rust_crate_map_toplevel".with_c_str(|buf| {
2696             unsafe {
2697                 llvm::LLVMAddAlias(ccx.llmod, maptype,
2698                                    ccx.crate_map, buf);
2699             }
2700         })
2701     }
2702
2703     glue::emit_tydescs(ccx);
2704     if ccx.sess.opts.debuginfo != NoDebugInfo {
2705         debuginfo::finalize(ccx);
2706     }
2707
2708     // Translate the metadata.
2709     let metadata = write_metadata(ccx, &krate);
2710     if ccx.sess.trans_stats() {
2711         println!("--- trans stats ---");
2712         println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2713         println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2714         println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2715         println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2716
2717         println!("n_fns: {}", ccx.stats.n_fns.get());
2718         println!("n_monos: {}", ccx.stats.n_monos.get());
2719         println!("n_inlines: {}", ccx.stats.n_inlines.get());
2720         println!("n_closures: {}", ccx.stats.n_closures.get());
2721         println!("fn stats:");
2722         {
2723             let mut fn_stats = ccx.stats.fn_stats.borrow_mut();
2724             fn_stats.get().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2725                 insns_b.cmp(&insns_a)
2726             });
2727             for tuple in fn_stats.get().iter() {
2728                 match *tuple {
2729                     (ref name, ms, insns) => {
2730                         println!("{} insns, {} ms, {}", insns, ms, *name);
2731                     }
2732                 }
2733             }
2734         }
2735     }
2736     if ccx.sess.count_llvm_insns() {
2737         let llvm_insns = ccx.stats.llvm_insns.borrow();
2738         for (k, v) in llvm_insns.get().iter() {
2739             println!("{:7u} {}", *v, *k);
2740         }
2741     }
2742
2743     let llcx = ccx.llcx;
2744     let link_meta = ccx.link_meta.clone();
2745     let llmod = ccx.llmod;
2746
2747     let mut reachable = {
2748         let reachable_map = ccx.reachable.borrow();
2749         reachable_map.get().iter().filter_map(|id| {
2750             let item_symbols = ccx.item_symbols.borrow();
2751             item_symbols.get().find(id).map(|s| s.to_owned())
2752         }).to_owned_vec()
2753     };
2754
2755     // Make sure that some other crucial symbols are not eliminated from the
2756     // module. This includes the main function, the crate map (used for debug
2757     // log settings and I/O), and finally the curious rust_stack_exhausted
2758     // symbol. This symbol is required for use by the libmorestack library that
2759     // we link in, so we must ensure that this symbol is not internalized (if
2760     // defined in the crate).
2761     reachable.push(ccx.crate_map_name.to_owned());
2762     reachable.push(~"main");
2763     reachable.push(~"rust_stack_exhausted");
2764     reachable.push(~"rust_eh_personality"); // referenced from .eh_frame section on some platforms
2765     reachable.push(~"rust_eh_personality_catch"); // referenced from rt/rust_try.ll
2766
2767     return CrateTranslation {
2768         context: llcx,
2769         module: llmod,
2770         link: link_meta,
2771         metadata_module: ccx.metadata_llmod,
2772         metadata: metadata,
2773         reachable: reachable,
2774     };
2775 }