]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/base.rs
add an align parameter to exchange_malloc
[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, Vector};
36 use lib;
37 use metadata::{csearch, encoder};
38 use middle::astencode;
39 use middle::lang_items::{LangItem, ExchangeMallocFnLangItem, StartFnLangItem};
40 use middle::trans::_match;
41 use middle::trans::adt;
42 use middle::trans::build::*;
43 use middle::trans::builder::{Builder, noname};
44 use middle::trans::callee;
45 use middle::trans::cleanup;
46 use middle::trans::cleanup::CleanupMethods;
47 use middle::trans::common::*;
48 use middle::trans::consts;
49 use middle::trans::controlflow;
50 use middle::trans::datum;
51 // use middle::trans::datum::{Datum, Lvalue, Rvalue, ByRef, ByValue};
52 use middle::trans::debuginfo;
53 use middle::trans::expr;
54 use middle::trans::foreign;
55 use middle::trans::glue;
56 use middle::trans::inline;
57 use middle::trans::machine;
58 use middle::trans::machine::{llalign_of_min, llsize_of};
59 use middle::trans::meth;
60 use middle::trans::monomorphize;
61 use middle::trans::tvec;
62 use middle::trans::type_::Type;
63 use middle::trans::type_of;
64 use middle::trans::type_of::*;
65 use middle::trans::value::Value;
66 use middle::ty;
67 use middle::typeck;
68 use util::common::indenter;
69 use util::ppaux::{Repr, ty_to_str};
70 use util::sha2::Sha256;
71 use util::nodemap::NodeMap;
72
73 use arena::TypedArena;
74 use libc::c_uint;
75 use std::c_str::ToCStr;
76 use std::cell::{Cell, RefCell};
77 use std::rc::Rc;
78 use syntax::abi::{X86, X86_64, Arm, Mips, Rust, RustIntrinsic};
79 use syntax::ast_util::{local_def, is_local};
80 use syntax::attr::AttrMetaMethods;
81 use syntax::attr;
82 use syntax::codemap::Span;
83 use syntax::parse::token::InternedString;
84 use syntax::visit::Visitor;
85 use syntax::visit;
86 use syntax::{ast, ast_util, ast_map};
87
88 use time;
89
90 local_data_key!(task_local_insn_key: RefCell<Vec<&'static str>>)
91
92 pub fn with_insn_ctxt(blk: |&[&'static str]|) {
93     match task_local_insn_key.get() {
94         Some(ctx) => blk(ctx.borrow().as_slice()),
95         None => ()
96     }
97 }
98
99 pub fn init_insn_ctxt() {
100     task_local_insn_key.replace(Some(RefCell::new(Vec::new())));
101 }
102
103 pub struct _InsnCtxt { _x: () }
104
105 #[unsafe_destructor]
106 impl Drop for _InsnCtxt {
107     fn drop(&mut self) {
108         match task_local_insn_key.get() {
109             Some(ctx) => { ctx.borrow_mut().pop(); }
110             None => {}
111         }
112     }
113 }
114
115 pub fn push_ctxt(s: &'static str) -> _InsnCtxt {
116     debug!("new InsnCtxt: {}", s);
117     match task_local_insn_key.get() {
118         Some(ctx) => ctx.borrow_mut().push(s),
119         None => {}
120     }
121     _InsnCtxt { _x: () }
122 }
123
124 pub struct StatRecorder<'a> {
125     ccx: &'a CrateContext,
126     name: Option<~str>,
127     start: u64,
128     istart: uint,
129 }
130
131 impl<'a> StatRecorder<'a> {
132     pub fn new(ccx: &'a CrateContext, name: ~str) -> StatRecorder<'a> {
133         let start = if ccx.sess().trans_stats() {
134             time::precise_time_ns()
135         } else {
136             0
137         };
138         let istart = ccx.stats.n_llvm_insns.get();
139         StatRecorder {
140             ccx: ccx,
141             name: Some(name),
142             start: start,
143             istart: istart,
144         }
145     }
146 }
147
148 #[unsafe_destructor]
149 impl<'a> Drop for StatRecorder<'a> {
150     fn drop(&mut self) {
151         if self.ccx.sess().trans_stats() {
152             let end = time::precise_time_ns();
153             let elapsed = ((end - self.start) / 1_000_000) as uint;
154             let iend = self.ccx.stats.n_llvm_insns.get();
155             self.ccx.stats.fn_stats.borrow_mut().push((self.name.take_unwrap(),
156                                                        elapsed,
157                                                        iend - self.istart));
158             self.ccx.stats.n_fns.set(self.ccx.stats.n_fns.get() + 1);
159             // Reset LLVM insn count to avoid compound costs.
160             self.ccx.stats.n_llvm_insns.set(self.istart);
161         }
162     }
163 }
164
165 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
166 fn decl_fn(llmod: ModuleRef, name: &str, cc: lib::llvm::CallConv,
167            ty: Type, output: ty::t) -> ValueRef {
168     let llfn: ValueRef = name.with_c_str(|buf| {
169         unsafe {
170             llvm::LLVMGetOrInsertFunction(llmod, buf, ty.to_ref())
171         }
172     });
173
174     match ty::get(output).sty {
175         // functions returning bottom may unwind, but can never return normally
176         ty::ty_bot => {
177             unsafe {
178                 llvm::LLVMAddFunctionAttr(llfn, lib::llvm::NoReturnAttribute as c_uint)
179             }
180         }
181         // `~` pointer return values never alias because ownership is transferred
182         ty::ty_uniq(..) // | ty::ty_trait(_, _, ty::UniqTraitStore, _, _)
183          => {
184             unsafe {
185                 llvm::LLVMAddReturnAttribute(llfn, lib::llvm::NoAliasAttribute as c_uint);
186             }
187         }
188         _ => {}
189     }
190
191     lib::llvm::SetFunctionCallConv(llfn, cc);
192     // Function addresses in Rust are never significant, allowing functions to be merged.
193     lib::llvm::SetUnnamedAddr(llfn, true);
194     set_split_stack(llfn);
195
196     llfn
197 }
198
199 // only use this for foreign function ABIs and glue, use `decl_rust_fn` for Rust functions
200 pub fn decl_cdecl_fn(llmod: ModuleRef,
201                      name: &str,
202                      ty: Type,
203                      output: ty::t) -> ValueRef {
204     decl_fn(llmod, name, lib::llvm::CCallConv, ty, output)
205 }
206
207 // only use this for foreign function ABIs and glue, use `get_extern_rust_fn` for Rust functions
208 pub fn get_extern_fn(externs: &mut ExternMap, llmod: ModuleRef,
209                      name: &str, cc: lib::llvm::CallConv,
210                      ty: Type, output: ty::t) -> ValueRef {
211     match externs.find_equiv(&name) {
212         Some(n) => return *n,
213         None => {}
214     }
215     let f = decl_fn(llmod, name, cc, ty, output);
216     externs.insert(name.to_owned(), f);
217     f
218 }
219
220 fn get_extern_rust_fn(ccx: &CrateContext, inputs: &[ty::t], output: ty::t,
221                       name: &str, did: ast::DefId) -> ValueRef {
222     match ccx.externs.borrow().find_equiv(&name) {
223         Some(n) => return *n,
224         None => ()
225     }
226
227     let f = decl_rust_fn(ccx, false, inputs, output, name);
228     csearch::get_item_attrs(&ccx.sess().cstore, did, |meta_items| {
229         set_llvm_fn_attrs(meta_items.iter().map(|&x| attr::mk_attr(x))
230                                     .collect::<Vec<_>>().as_slice(), f)
231     });
232
233     ccx.externs.borrow_mut().insert(name.to_owned(), f);
234     f
235 }
236
237 pub fn decl_rust_fn(ccx: &CrateContext, has_env: bool,
238                     inputs: &[ty::t], output: ty::t,
239                     name: &str) -> ValueRef {
240     use middle::ty::{BrAnon, ReLateBound};
241
242     let llfty = type_of_rust_fn(ccx, has_env, inputs, output);
243     let llfn = decl_cdecl_fn(ccx.llmod, name, llfty, output);
244
245     let uses_outptr = type_of::return_uses_outptr(ccx, output);
246     let offset = if uses_outptr { 1 } else { 0 };
247     let offset = if has_env { offset + 1 } else { offset };
248
249     for (i, &arg_ty) in inputs.iter().enumerate() {
250         let llarg = unsafe { llvm::LLVMGetParam(llfn, (offset + i) as c_uint) };
251         match ty::get(arg_ty).sty {
252             // `~` pointer parameters never alias because ownership is transferred
253             ty::ty_uniq(..) => {
254                 unsafe {
255                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
256                 }
257             }
258             // `&mut` pointer parameters never alias other parameters, or mutable global data
259             ty::ty_rptr(_, mt) if mt.mutbl == ast::MutMutable => {
260                 unsafe {
261                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
262                 }
263             }
264             // When a reference in an argument has no named lifetime, it's impossible for that
265             // reference to escape this function (returned or stored beyond the call by a closure).
266             ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
267                 debug!("marking argument of {} as nocapture because of anonymous lifetime", name);
268                 unsafe {
269                     llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
270                 }
271             }
272             _ => {
273                 // For non-immediate arguments the callee gets its own copy of
274                 // the value on the stack, so there are no aliases
275                 if !type_is_immediate(ccx, arg_ty) {
276                     unsafe {
277                         llvm::LLVMAddAttribute(llarg, lib::llvm::NoAliasAttribute as c_uint);
278                         llvm::LLVMAddAttribute(llarg, lib::llvm::NoCaptureAttribute as c_uint);
279                     }
280                 }
281             }
282         }
283     }
284
285     // The out pointer will never alias with any other pointers, as the object only exists at a
286     // language level after the call. It can also be tagged with SRet to indicate that it is
287     // guaranteed to point to a usable block of memory for the type.
288     if uses_outptr {
289         unsafe {
290             let outptr = llvm::LLVMGetParam(llfn, 0);
291             llvm::LLVMAddAttribute(outptr, lib::llvm::StructRetAttribute as c_uint);
292             llvm::LLVMAddAttribute(outptr, lib::llvm::NoAliasAttribute as c_uint);
293         }
294     }
295
296     llfn
297 }
298
299 pub fn decl_internal_rust_fn(ccx: &CrateContext, has_env: bool,
300                              inputs: &[ty::t], output: ty::t,
301                              name: &str) -> ValueRef {
302     let llfn = decl_rust_fn(ccx, has_env, inputs, output, name);
303     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
304     llfn
305 }
306
307 pub fn get_extern_const(externs: &mut ExternMap, llmod: ModuleRef,
308                         name: &str, ty: Type) -> ValueRef {
309     match externs.find_equiv(&name) {
310         Some(n) => return *n,
311         None => ()
312     }
313     unsafe {
314         let c = name.with_c_str(|buf| {
315             llvm::LLVMAddGlobal(llmod, ty.to_ref(), buf)
316         });
317         externs.insert(name.to_owned(), c);
318         return c;
319     }
320 }
321
322 // Returns a pointer to the body for the box. The box may be an opaque
323 // box. The result will be casted to the type of body_t, if it is statically
324 // known.
325 pub fn at_box_body(bcx: &Block, body_t: ty::t, boxptr: ValueRef) -> ValueRef {
326     let _icx = push_ctxt("at_box_body");
327     let ccx = bcx.ccx();
328     let ty = Type::at_box(ccx, type_of(ccx, body_t));
329     let boxptr = PointerCast(bcx, boxptr, ty.ptr_to());
330     GEPi(bcx, boxptr, [0u, abi::box_field_body])
331 }
332
333 fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
334     match bcx.tcx().lang_items.require(it) {
335         Ok(id) => id,
336         Err(s) => {
337             bcx.sess().fatal(format!("allocation of `{}` {}",
338                                      bcx.ty_to_str(info_ty), s));
339         }
340     }
341 }
342
343 // The following malloc_raw_dyn* functions allocate a box to contain
344 // a given type, but with a potentially dynamic size.
345
346 pub fn malloc_raw_dyn<'a>(bcx: &'a Block<'a>,
347                           ptr_ty: ty::t,
348                           size: ValueRef,
349                           align: ValueRef)
350                           -> Result<'a> {
351     let _icx = push_ctxt("malloc_raw_exchange");
352     let ccx = bcx.ccx();
353
354     // Allocate space:
355     let r = callee::trans_lang_call(bcx,
356         require_alloc_fn(bcx, ptr_ty, ExchangeMallocFnLangItem),
357         [size, align],
358         None);
359
360     let llty_ptr = type_of::type_of(ccx, ptr_ty);
361     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty_ptr))
362 }
363
364 pub fn malloc_raw_dyn_managed<'a>(
365                       bcx: &'a Block<'a>,
366                       t: ty::t,
367                       alloc_fn: LangItem,
368                       size: ValueRef)
369                       -> Result<'a> {
370     let _icx = push_ctxt("malloc_raw_managed");
371     let ccx = bcx.ccx();
372
373     let langcall = require_alloc_fn(bcx, t, alloc_fn);
374
375     // Grab the TypeRef type of box_ptr_ty.
376     let box_ptr_ty = ty::mk_box(bcx.tcx(), t);
377     let llty = type_of(ccx, box_ptr_ty);
378     let llalign = C_uint(ccx, llalign_of_min(ccx, llty) as uint);
379
380     // Allocate space:
381     let drop_glue = glue::get_drop_glue(ccx, t);
382     let r = callee::trans_lang_call(
383         bcx,
384         langcall,
385         [
386             PointerCast(bcx, drop_glue, Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to()),
387             size,
388             llalign
389         ],
390         None);
391     Result::new(r.bcx, PointerCast(r.bcx, r.val, llty))
392 }
393
394 // Type descriptor and type glue stuff
395
396 pub fn get_tydesc(ccx: &CrateContext, t: ty::t) -> Rc<tydesc_info> {
397     match ccx.tydescs.borrow().find(&t) {
398         Some(inf) => return inf.clone(),
399         _ => { }
400     }
401
402     ccx.stats.n_static_tydescs.set(ccx.stats.n_static_tydescs.get() + 1u);
403     let inf = Rc::new(glue::declare_tydesc(ccx, t));
404
405     ccx.tydescs.borrow_mut().insert(t, inf.clone());
406     inf
407 }
408
409 #[allow(dead_code)] // useful
410 pub fn set_optimize_for_size(f: ValueRef) {
411     lib::llvm::SetFunctionAttribute(f, lib::llvm::OptimizeForSizeAttribute)
412 }
413
414 pub fn set_no_inline(f: ValueRef) {
415     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoInlineAttribute)
416 }
417
418 #[allow(dead_code)] // useful
419 pub fn set_no_unwind(f: ValueRef) {
420     lib::llvm::SetFunctionAttribute(f, lib::llvm::NoUnwindAttribute)
421 }
422
423 // Tell LLVM to emit the information necessary to unwind the stack for the
424 // function f.
425 pub fn set_uwtable(f: ValueRef) {
426     lib::llvm::SetFunctionAttribute(f, lib::llvm::UWTableAttribute)
427 }
428
429 pub fn set_inline_hint(f: ValueRef) {
430     lib::llvm::SetFunctionAttribute(f, lib::llvm::InlineHintAttribute)
431 }
432
433 pub fn set_llvm_fn_attrs(attrs: &[ast::Attribute], llfn: ValueRef) {
434     use syntax::attr::*;
435     // Set the inline hint if there is one
436     match find_inline_attr(attrs) {
437         InlineHint   => set_inline_hint(llfn),
438         InlineAlways => set_always_inline(llfn),
439         InlineNever  => set_no_inline(llfn),
440         InlineNone   => { /* fallthrough */ }
441     }
442
443     // Add the no-split-stack attribute if requested
444     if contains_name(attrs, "no_split_stack") {
445         unset_split_stack(llfn);
446     }
447
448     if contains_name(attrs, "cold") {
449         unsafe { llvm::LLVMAddColdAttribute(llfn) }
450     }
451 }
452
453 pub fn set_always_inline(f: ValueRef) {
454     lib::llvm::SetFunctionAttribute(f, lib::llvm::AlwaysInlineAttribute)
455 }
456
457 pub fn set_split_stack(f: ValueRef) {
458     "split-stack".with_c_str(|buf| {
459         unsafe { llvm::LLVMAddFunctionAttrString(f, buf); }
460     })
461 }
462
463 pub fn unset_split_stack(f: ValueRef) {
464     "split-stack".with_c_str(|buf| {
465         unsafe { llvm::LLVMRemoveFunctionAttrString(f, buf); }
466     })
467 }
468
469 // Double-check that we never ask LLVM to declare the same symbol twice. It
470 // silently mangles such symbols, breaking our linkage model.
471 pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: ~str) {
472     if ccx.all_llvm_symbols.borrow().contains(&sym) {
473         ccx.sess().bug("duplicate LLVM symbol: ".to_owned() + sym);
474     }
475     ccx.all_llvm_symbols.borrow_mut().insert(sym);
476 }
477
478
479 pub fn get_res_dtor(ccx: &CrateContext,
480                     did: ast::DefId,
481                     parent_id: ast::DefId,
482                     substs: &ty::substs)
483                  -> ValueRef {
484     let _icx = push_ctxt("trans_res_dtor");
485     let did = if did.krate != ast::LOCAL_CRATE {
486         inline::maybe_instantiate_inline(ccx, did)
487     } else {
488         did
489     };
490
491     if !substs.tps.is_empty() || !substs.self_ty.is_none() {
492         assert_eq!(did.krate, ast::LOCAL_CRATE);
493
494         let vtables = typeck::check::vtable::trans_resolve_method(ccx.tcx(), did.node, substs);
495         let (val, _) = monomorphize::monomorphic_fn(ccx, did, substs, vtables, None, None);
496
497         val
498     } else if did.krate == ast::LOCAL_CRATE {
499         get_item_val(ccx, did.node)
500     } else {
501         let tcx = ccx.tcx();
502         let name = csearch::get_symbol(&ccx.sess().cstore, did);
503         let class_ty = ty::subst(tcx, substs,
504                                  ty::lookup_item_type(tcx, parent_id).ty);
505         let llty = type_of_dtor(ccx, class_ty);
506
507         get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
508                       lib::llvm::CCallConv, llty, ty::mk_nil())
509     }
510 }
511
512 // Structural comparison: a rather involved form of glue.
513 pub fn maybe_name_value(cx: &CrateContext, v: ValueRef, s: &str) {
514     if cx.sess().opts.cg.save_temps {
515         s.with_c_str(|buf| {
516             unsafe {
517                 llvm::LLVMSetValueName(v, buf)
518             }
519         })
520     }
521 }
522
523
524 // Used only for creating scalar comparison glue.
525 pub enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
526
527 // NB: This produces an i1, not a Rust bool (i8).
528 pub fn compare_scalar_types<'a>(
529                             cx: &'a Block<'a>,
530                             lhs: ValueRef,
531                             rhs: ValueRef,
532                             t: ty::t,
533                             op: ast::BinOp)
534                             -> Result<'a> {
535     let f = |a| Result::new(cx, compare_scalar_values(cx, lhs, rhs, a, op));
536
537     match ty::get(t).sty {
538         ty::ty_nil => f(nil_type),
539         ty::ty_bool | ty::ty_ptr(_) |
540         ty::ty_uint(_) | ty::ty_char => f(unsigned_int),
541         ty::ty_int(_) => f(signed_int),
542         ty::ty_float(_) => f(floating_point),
543             // Should never get here, because t is scalar.
544         _ => cx.sess().bug("non-scalar type passed to compare_scalar_types")
545     }
546 }
547
548
549 // A helper function to do the actual comparison of scalar values.
550 pub fn compare_scalar_values<'a>(
551                              cx: &'a Block<'a>,
552                              lhs: ValueRef,
553                              rhs: ValueRef,
554                              nt: scalar_type,
555                              op: ast::BinOp)
556                              -> ValueRef {
557     let _icx = push_ctxt("compare_scalar_values");
558     fn die(cx: &Block) -> ! {
559         cx.sess().bug("compare_scalar_values: must be a comparison operator");
560     }
561     match nt {
562       nil_type => {
563         // We don't need to do actual comparisons for nil.
564         // () == () holds but () < () does not.
565         match op {
566           ast::BiEq | ast::BiLe | ast::BiGe => return C_i1(cx.ccx(), true),
567           ast::BiNe | ast::BiLt | ast::BiGt => return C_i1(cx.ccx(), false),
568           // refinements would be nice
569           _ => die(cx)
570         }
571       }
572       floating_point => {
573         let cmp = match op {
574           ast::BiEq => lib::llvm::RealOEQ,
575           ast::BiNe => lib::llvm::RealUNE,
576           ast::BiLt => lib::llvm::RealOLT,
577           ast::BiLe => lib::llvm::RealOLE,
578           ast::BiGt => lib::llvm::RealOGT,
579           ast::BiGe => lib::llvm::RealOGE,
580           _ => die(cx)
581         };
582         return FCmp(cx, cmp, lhs, rhs);
583       }
584       signed_int => {
585         let cmp = match op {
586           ast::BiEq => lib::llvm::IntEQ,
587           ast::BiNe => lib::llvm::IntNE,
588           ast::BiLt => lib::llvm::IntSLT,
589           ast::BiLe => lib::llvm::IntSLE,
590           ast::BiGt => lib::llvm::IntSGT,
591           ast::BiGe => lib::llvm::IntSGE,
592           _ => die(cx)
593         };
594         return ICmp(cx, cmp, lhs, rhs);
595       }
596       unsigned_int => {
597         let cmp = match op {
598           ast::BiEq => lib::llvm::IntEQ,
599           ast::BiNe => lib::llvm::IntNE,
600           ast::BiLt => lib::llvm::IntULT,
601           ast::BiLe => lib::llvm::IntULE,
602           ast::BiGt => lib::llvm::IntUGT,
603           ast::BiGe => lib::llvm::IntUGE,
604           _ => die(cx)
605         };
606         return ICmp(cx, cmp, lhs, rhs);
607       }
608     }
609 }
610
611 pub fn compare_simd_types(
612                     cx: &Block,
613                     lhs: ValueRef,
614                     rhs: ValueRef,
615                     t: ty::t,
616                     size: uint,
617                     op: ast::BinOp)
618                     -> ValueRef {
619     match ty::get(t).sty {
620         ty::ty_float(_) => {
621             // The comparison operators for floating point vectors are challenging.
622             // LLVM outputs a `< size x i1 >`, but if we perform a sign extension
623             // then bitcast to a floating point vector, the result will be `-NaN`
624             // for each truth value. Because of this they are unsupported.
625             cx.sess().bug("compare_simd_types: comparison operators \
626                            not supported for floating point SIMD types")
627         },
628         ty::ty_uint(_) | ty::ty_int(_) => {
629             let cmp = match op {
630                 ast::BiEq => lib::llvm::IntEQ,
631                 ast::BiNe => lib::llvm::IntNE,
632                 ast::BiLt => lib::llvm::IntSLT,
633                 ast::BiLe => lib::llvm::IntSLE,
634                 ast::BiGt => lib::llvm::IntSGT,
635                 ast::BiGe => lib::llvm::IntSGE,
636                 _ => cx.sess().bug("compare_simd_types: must be a comparison operator"),
637             };
638             let return_ty = Type::vector(&type_of(cx.ccx(), t), size as u64);
639             // LLVM outputs an `< size x i1 >`, so we need to perform a sign extension
640             // to get the correctly sized type. This will compile to a single instruction
641             // once the IR is converted to assembly if the SIMD instruction is supported
642             // by the target architecture.
643             SExt(cx, ICmp(cx, cmp, lhs, rhs), return_ty)
644         },
645         _ => cx.sess().bug("compare_simd_types: invalid SIMD type"),
646     }
647 }
648
649 pub type val_and_ty_fn<'r,'b> =
650     |&'b Block<'b>, ValueRef, ty::t|: 'r -> &'b Block<'b>;
651
652 // Iterates through the elements of a structural type.
653 pub fn iter_structural_ty<'r,
654                           'b>(
655                           cx: &'b Block<'b>,
656                           av: ValueRef,
657                           t: ty::t,
658                           f: val_and_ty_fn<'r,'b>)
659                           -> &'b Block<'b> {
660     let _icx = push_ctxt("iter_structural_ty");
661
662     fn iter_variant<'r,
663                     'b>(
664                     cx: &'b Block<'b>,
665                     repr: &adt::Repr,
666                     av: ValueRef,
667                     variant: &ty::VariantInfo,
668                     substs: &ty::substs,
669                     f: val_and_ty_fn<'r,'b>)
670                     -> &'b Block<'b> {
671         let _icx = push_ctxt("iter_variant");
672         let tcx = cx.tcx();
673         let mut cx = cx;
674
675         for (i, &arg) in variant.args.iter().enumerate() {
676             cx = f(cx,
677                    adt::trans_field_ptr(cx, repr, av, variant.disr_val, i),
678                    ty::subst(tcx, substs, arg));
679         }
680         return cx;
681     }
682
683     let mut cx = cx;
684     match ty::get(t).sty {
685       ty::ty_struct(..) => {
686           let repr = adt::represent_type(cx.ccx(), t);
687           expr::with_field_tys(cx.tcx(), t, None, |discr, field_tys| {
688               for (i, field_ty) in field_tys.iter().enumerate() {
689                   let llfld_a = adt::trans_field_ptr(cx, &*repr, av, discr, i);
690                   cx = f(cx, llfld_a, field_ty.mt.ty);
691               }
692           })
693       }
694       ty::ty_vec(_, Some(n)) => {
695         let unit_ty = ty::sequence_element_type(cx.tcx(), t);
696         let (base, len) = tvec::get_fixed_base_and_byte_len(cx, av, unit_ty, n);
697         cx = tvec::iter_vec_raw(cx, base, unit_ty, len, f);
698       }
699       ty::ty_tup(ref args) => {
700           let repr = adt::represent_type(cx.ccx(), t);
701           for (i, arg) in args.iter().enumerate() {
702               let llfld_a = adt::trans_field_ptr(cx, &*repr, av, 0, i);
703               cx = f(cx, llfld_a, *arg);
704           }
705       }
706       ty::ty_enum(tid, ref substs) => {
707           let fcx = cx.fcx;
708           let ccx = fcx.ccx;
709
710           let repr = adt::represent_type(ccx, t);
711           let variants = ty::enum_variants(ccx.tcx(), tid);
712           let n_variants = (*variants).len();
713
714           // NB: we must hit the discriminant first so that structural
715           // comparison know not to proceed when the discriminants differ.
716
717           match adt::trans_switch(cx, &*repr, av) {
718               (_match::single, None) => {
719                   cx = iter_variant(cx, &*repr, av, &**variants.get(0),
720                                     substs, f);
721               }
722               (_match::switch, Some(lldiscrim_a)) => {
723                   cx = f(cx, lldiscrim_a, ty::mk_int());
724                   let unr_cx = fcx.new_temp_block("enum-iter-unr");
725                   Unreachable(unr_cx);
726                   let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb,
727                                         n_variants);
728                   let next_cx = fcx.new_temp_block("enum-iter-next");
729
730                   for variant in (*variants).iter() {
731                       let variant_cx =
732                           fcx.new_temp_block("enum-iter-variant-".to_owned() +
733                                              variant.disr_val.to_str());
734                       match adt::trans_case(cx, &*repr, variant.disr_val) {
735                           _match::single_result(r) => {
736                               AddCase(llswitch, r.val, variant_cx.llbb)
737                           }
738                           _ => ccx.sess().unimpl("value from adt::trans_case \
739                                                   in iter_structural_ty")
740                       }
741                       let variant_cx =
742                           iter_variant(variant_cx,
743                                        &*repr,
744                                        av,
745                                        &**variant,
746                                        substs,
747                                        |x,y,z| f(x,y,z));
748                       Br(variant_cx, next_cx.llbb);
749                   }
750                   cx = next_cx;
751               }
752               _ => ccx.sess().unimpl("value from adt::trans_switch \
753                                       in iter_structural_ty")
754           }
755       }
756       _ => cx.sess().unimpl("type in iter_structural_ty")
757     }
758     return cx;
759 }
760
761 pub fn cast_shift_expr_rhs<'a>(
762                            cx: &'a Block<'a>,
763                            op: ast::BinOp,
764                            lhs: ValueRef,
765                            rhs: ValueRef)
766                            -> ValueRef {
767     cast_shift_rhs(op, lhs, rhs,
768                    |a,b| Trunc(cx, a, b),
769                    |a,b| ZExt(cx, a, b))
770 }
771
772 pub fn cast_shift_const_rhs(op: ast::BinOp,
773                             lhs: ValueRef, rhs: ValueRef) -> ValueRef {
774     cast_shift_rhs(op, lhs, rhs,
775                    |a, b| unsafe { llvm::LLVMConstTrunc(a, b.to_ref()) },
776                    |a, b| unsafe { llvm::LLVMConstZExt(a, b.to_ref()) })
777 }
778
779 pub fn cast_shift_rhs(op: ast::BinOp,
780                       lhs: ValueRef,
781                       rhs: ValueRef,
782                       trunc: |ValueRef, Type| -> ValueRef,
783                       zext: |ValueRef, Type| -> ValueRef)
784                       -> ValueRef {
785     // Shifts may have any size int on the rhs
786     unsafe {
787         if ast_util::is_shift_binop(op) {
788             let mut rhs_llty = val_ty(rhs);
789             let mut lhs_llty = val_ty(lhs);
790             if rhs_llty.kind() == Vector { rhs_llty = rhs_llty.element_type() }
791             if lhs_llty.kind() == Vector { lhs_llty = lhs_llty.element_type() }
792             let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty.to_ref());
793             let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty.to_ref());
794             if lhs_sz < rhs_sz {
795                 trunc(rhs, lhs_llty)
796             } else if lhs_sz > rhs_sz {
797                 // FIXME (#1877: If shifting by negative
798                 // values becomes not undefined then this is wrong.
799                 zext(rhs, lhs_llty)
800             } else {
801                 rhs
802             }
803         } else {
804             rhs
805         }
806     }
807 }
808
809 pub fn fail_if_zero<'a>(
810                     cx: &'a Block<'a>,
811                     span: Span,
812                     divrem: ast::BinOp,
813                     rhs: ValueRef,
814                     rhs_t: ty::t)
815                     -> &'a Block<'a> {
816     let text = if divrem == ast::BiDiv {
817         "attempted to divide by zero"
818     } else {
819         "attempted remainder with a divisor of zero"
820     };
821     let is_zero = match ty::get(rhs_t).sty {
822       ty::ty_int(t) => {
823         let zero = C_integral(Type::int_from_ty(cx.ccx(), t), 0u64, false);
824         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
825       }
826       ty::ty_uint(t) => {
827         let zero = C_integral(Type::uint_from_ty(cx.ccx(), t), 0u64, false);
828         ICmp(cx, lib::llvm::IntEQ, rhs, zero)
829       }
830       _ => {
831         cx.sess().bug("fail-if-zero on unexpected type: ".to_owned() +
832                       ty_to_str(cx.tcx(), rhs_t));
833       }
834     };
835     with_cond(cx, is_zero, |bcx| {
836         controlflow::trans_fail(bcx, span, InternedString::new(text))
837     })
838 }
839
840 pub fn trans_external_path(ccx: &CrateContext, did: ast::DefId, t: ty::t) -> ValueRef {
841     let name = csearch::get_symbol(&ccx.sess().cstore, did);
842     match ty::get(t).sty {
843         ty::ty_bare_fn(ref fn_ty) => {
844             match fn_ty.abi.for_target(ccx.sess().targ_cfg.os,
845                                        ccx.sess().targ_cfg.arch) {
846                 Some(Rust) | Some(RustIntrinsic) => {
847                     get_extern_rust_fn(ccx,
848                                        fn_ty.sig.inputs.as_slice(),
849                                        fn_ty.sig.output,
850                                        name,
851                                        did)
852                 }
853                 Some(..) | None => {
854                     let c = foreign::llvm_calling_convention(ccx, fn_ty.abi);
855                     let cconv = c.unwrap_or(lib::llvm::CCallConv);
856                     let llty = type_of_fn_from_ty(ccx, t);
857                     get_extern_fn(&mut *ccx.externs.borrow_mut(), ccx.llmod,
858                                   name, cconv, llty, fn_ty.sig.output)
859                 }
860             }
861         }
862         ty::ty_closure(ref f) => {
863             get_extern_rust_fn(ccx,
864                                f.sig.inputs.as_slice(),
865                                f.sig.output,
866                                name,
867                                did)
868         }
869         _ => {
870             let llty = type_of(ccx, t);
871             get_extern_const(&mut *ccx.externs.borrow_mut(), ccx.llmod, name,
872                              llty)
873         }
874     }
875 }
876
877 pub fn invoke<'a>(
878               bcx: &'a Block<'a>,
879               llfn: ValueRef,
880               llargs: Vec<ValueRef> ,
881               attributes: &[(uint, lib::llvm::Attribute)],
882               call_info: Option<NodeInfo>)
883               -> (ValueRef, &'a Block<'a>) {
884     let _icx = push_ctxt("invoke_");
885     if bcx.unreachable.get() {
886         return (C_null(Type::i8(bcx.ccx())), bcx);
887     }
888
889     match bcx.opt_node_id {
890         None => {
891             debug!("invoke at ???");
892         }
893         Some(id) => {
894             debug!("invoke at {}", bcx.tcx().map.node_to_str(id));
895         }
896     }
897
898     if need_invoke(bcx) {
899         debug!("invoking {} at {}", llfn, bcx.llbb);
900         for &llarg in llargs.iter() {
901             debug!("arg: {}", llarg);
902         }
903         let normal_bcx = bcx.fcx.new_temp_block("normal-return");
904         let landing_pad = bcx.fcx.get_landing_pad();
905
906         match call_info {
907             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
908             None => debuginfo::clear_source_location(bcx.fcx)
909         };
910
911         let llresult = Invoke(bcx,
912                               llfn,
913                               llargs.as_slice(),
914                               normal_bcx.llbb,
915                               landing_pad,
916                               attributes);
917         return (llresult, normal_bcx);
918     } else {
919         debug!("calling {} at {}", llfn, bcx.llbb);
920         for &llarg in llargs.iter() {
921             debug!("arg: {}", llarg);
922         }
923
924         match call_info {
925             Some(info) => debuginfo::set_source_location(bcx.fcx, info.id, info.span),
926             None => debuginfo::clear_source_location(bcx.fcx)
927         };
928
929         let llresult = Call(bcx, llfn, llargs.as_slice(), attributes);
930         return (llresult, bcx);
931     }
932 }
933
934 pub fn need_invoke(bcx: &Block) -> bool {
935     if bcx.sess().no_landing_pads() {
936         return false;
937     }
938
939     // Avoid using invoke if we are already inside a landing pad.
940     if bcx.is_lpad {
941         return false;
942     }
943
944     bcx.fcx.needs_invoke()
945 }
946
947 pub fn load_if_immediate(cx: &Block, v: ValueRef, t: ty::t) -> ValueRef {
948     let _icx = push_ctxt("load_if_immediate");
949     if type_is_immediate(cx.ccx(), t) { return Load(cx, v); }
950     return v;
951 }
952
953 pub fn ignore_lhs(_bcx: &Block, local: &ast::Local) -> bool {
954     match local.pat.node {
955         ast::PatWild => true, _ => false
956     }
957 }
958
959 pub fn init_local<'a>(bcx: &'a Block<'a>, local: &ast::Local)
960                   -> &'a Block<'a> {
961
962     debug!("init_local(bcx={}, local.id={:?})",
963            bcx.to_str(), local.id);
964     let _indenter = indenter();
965
966     let _icx = push_ctxt("init_local");
967
968     if ignore_lhs(bcx, local) {
969         // Handle let _ = e; just like e;
970         match local.init {
971             Some(init) => {
972                 return controlflow::trans_stmt_semi(bcx, init)
973             }
974             None => { return bcx; }
975         }
976     }
977
978     _match::store_local(bcx, local)
979 }
980
981 pub fn raw_block<'a>(
982                  fcx: &'a FunctionContext<'a>,
983                  is_lpad: bool,
984                  llbb: BasicBlockRef)
985                  -> &'a Block<'a> {
986     Block::new(llbb, is_lpad, None, fcx)
987 }
988
989 pub fn with_cond<'a>(
990                  bcx: &'a Block<'a>,
991                  val: ValueRef,
992                  f: |&'a Block<'a>| -> &'a Block<'a>)
993                  -> &'a Block<'a> {
994     let _icx = push_ctxt("with_cond");
995     let fcx = bcx.fcx;
996     let next_cx = fcx.new_temp_block("next");
997     let cond_cx = fcx.new_temp_block("cond");
998     CondBr(bcx, val, cond_cx.llbb, next_cx.llbb);
999     let after_cx = f(cond_cx);
1000     if !after_cx.terminated.get() {
1001         Br(after_cx, next_cx.llbb);
1002     }
1003     next_cx
1004 }
1005
1006 pub fn call_memcpy(cx: &Block, dst: ValueRef, src: ValueRef, n_bytes: ValueRef, align: u32) {
1007     let _icx = push_ctxt("call_memcpy");
1008     let ccx = cx.ccx();
1009     let key = match ccx.sess().targ_cfg.arch {
1010         X86 | Arm | Mips => "llvm.memcpy.p0i8.p0i8.i32",
1011         X86_64 => "llvm.memcpy.p0i8.p0i8.i64"
1012     };
1013     let memcpy = ccx.get_intrinsic(&key);
1014     let src_ptr = PointerCast(cx, src, Type::i8p(ccx));
1015     let dst_ptr = PointerCast(cx, dst, Type::i8p(ccx));
1016     let size = IntCast(cx, n_bytes, ccx.int_type);
1017     let align = C_i32(ccx, align as i32);
1018     let volatile = C_i1(ccx, false);
1019     Call(cx, memcpy, [dst_ptr, src_ptr, size, align, volatile], []);
1020 }
1021
1022 pub fn memcpy_ty(bcx: &Block, dst: ValueRef, src: ValueRef, t: ty::t) {
1023     let _icx = push_ctxt("memcpy_ty");
1024     let ccx = bcx.ccx();
1025     if ty::type_is_structural(t) {
1026         let llty = type_of::type_of(ccx, t);
1027         let llsz = llsize_of(ccx, llty);
1028         let llalign = llalign_of_min(ccx, llty);
1029         call_memcpy(bcx, dst, src, llsz, llalign as u32);
1030     } else {
1031         Store(bcx, Load(bcx, src), dst);
1032     }
1033 }
1034
1035 pub fn zero_mem(cx: &Block, llptr: ValueRef, t: ty::t) {
1036     if cx.unreachable.get() { return; }
1037     let _icx = push_ctxt("zero_mem");
1038     let bcx = cx;
1039     let ccx = cx.ccx();
1040     let llty = type_of::type_of(ccx, t);
1041     memzero(&B(bcx), llptr, llty);
1042 }
1043
1044 // Always use this function instead of storing a zero constant to the memory
1045 // in question. If you store a zero constant, LLVM will drown in vreg
1046 // allocation for large data structures, and the generated code will be
1047 // awful. (A telltale sign of this is large quantities of
1048 // `mov [byte ptr foo],0` in the generated code.)
1049 fn memzero(b: &Builder, llptr: ValueRef, ty: Type) {
1050     let _icx = push_ctxt("memzero");
1051     let ccx = b.ccx;
1052
1053     let intrinsic_key = match ccx.sess().targ_cfg.arch {
1054         X86 | Arm | Mips => "llvm.memset.p0i8.i32",
1055         X86_64 => "llvm.memset.p0i8.i64"
1056     };
1057
1058     let llintrinsicfn = ccx.get_intrinsic(&intrinsic_key);
1059     let llptr = b.pointercast(llptr, Type::i8(ccx).ptr_to());
1060     let llzeroval = C_u8(ccx, 0);
1061     let size = machine::llsize_of(ccx, ty);
1062     let align = C_i32(ccx, llalign_of_min(ccx, ty) as i32);
1063     let volatile = C_i1(ccx, false);
1064     b.call(llintrinsicfn, [llptr, llzeroval, size, align, volatile], []);
1065 }
1066
1067 pub fn alloc_ty(bcx: &Block, t: ty::t, name: &str) -> ValueRef {
1068     let _icx = push_ctxt("alloc_ty");
1069     let ccx = bcx.ccx();
1070     let ty = type_of::type_of(ccx, t);
1071     assert!(!ty::type_has_params(t));
1072     let val = alloca(bcx, ty, name);
1073     return val;
1074 }
1075
1076 pub fn alloca(cx: &Block, ty: Type, name: &str) -> ValueRef {
1077     alloca_maybe_zeroed(cx, ty, name, false)
1078 }
1079
1080 pub fn alloca_maybe_zeroed(cx: &Block, ty: Type, name: &str, zero: bool) -> ValueRef {
1081     let _icx = push_ctxt("alloca");
1082     if cx.unreachable.get() {
1083         unsafe {
1084             return llvm::LLVMGetUndef(ty.ptr_to().to_ref());
1085         }
1086     }
1087     debuginfo::clear_source_location(cx.fcx);
1088     let p = Alloca(cx, ty, name);
1089     if zero {
1090         let b = cx.fcx.ccx.builder();
1091         b.position_before(cx.fcx.alloca_insert_pt.get().unwrap());
1092         memzero(&b, p, ty);
1093     }
1094     p
1095 }
1096
1097 pub fn arrayalloca(cx: &Block, ty: Type, v: ValueRef) -> ValueRef {
1098     let _icx = push_ctxt("arrayalloca");
1099     if cx.unreachable.get() {
1100         unsafe {
1101             return llvm::LLVMGetUndef(ty.to_ref());
1102         }
1103     }
1104     debuginfo::clear_source_location(cx.fcx);
1105     return ArrayAlloca(cx, ty, v);
1106 }
1107
1108 // Creates and returns space for, or returns the argument representing, the
1109 // slot where the return value of the function must go.
1110 pub fn make_return_pointer(fcx: &FunctionContext, output_type: ty::t)
1111                            -> ValueRef {
1112     unsafe {
1113         if type_of::return_uses_outptr(fcx.ccx, output_type) {
1114             llvm::LLVMGetParam(fcx.llfn, 0)
1115         } else {
1116             let lloutputtype = type_of::type_of(fcx.ccx, output_type);
1117             let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1118             Alloca(bcx, lloutputtype, "__make_return_pointer")
1119         }
1120     }
1121 }
1122
1123 // NB: must keep 4 fns in sync:
1124 //
1125 //  - type_of_fn
1126 //  - create_datums_for_fn_args.
1127 //  - new_fn_ctxt
1128 //  - trans_args
1129 //
1130 // Be warned! You must call `init_function` before doing anything with the
1131 // returned function context.
1132 pub fn new_fn_ctxt<'a>(ccx: &'a CrateContext,
1133                        llfndecl: ValueRef,
1134                        id: ast::NodeId,
1135                        has_env: bool,
1136                        output_type: ty::t,
1137                        param_substs: Option<&'a param_substs>,
1138                        sp: Option<Span>,
1139                        block_arena: &'a TypedArena<Block<'a>>)
1140                        -> FunctionContext<'a> {
1141     for p in param_substs.iter() { p.validate(); }
1142
1143     debug!("new_fn_ctxt(path={}, id={}, param_substs={})",
1144            if id == -1 {
1145                "".to_owned()
1146            } else {
1147                ccx.tcx.map.path_to_str(id).to_owned()
1148            },
1149            id, param_substs.map(|s| s.repr(ccx.tcx())));
1150
1151     let substd_output_type = output_type.substp(ccx.tcx(), param_substs);
1152     let uses_outptr = type_of::return_uses_outptr(ccx, substd_output_type);
1153     let debug_context = debuginfo::create_function_debug_context(ccx, id, param_substs, llfndecl);
1154
1155     let mut fcx = FunctionContext {
1156           llfn: llfndecl,
1157           llenv: None,
1158           llretptr: Cell::new(None),
1159           entry_bcx: RefCell::new(None),
1160           alloca_insert_pt: Cell::new(None),
1161           llreturn: Cell::new(None),
1162           personality: Cell::new(None),
1163           caller_expects_out_pointer: uses_outptr,
1164           llargs: RefCell::new(NodeMap::new()),
1165           lllocals: RefCell::new(NodeMap::new()),
1166           llupvars: RefCell::new(NodeMap::new()),
1167           id: id,
1168           param_substs: param_substs,
1169           span: sp,
1170           block_arena: block_arena,
1171           ccx: ccx,
1172           debug_context: debug_context,
1173           scopes: RefCell::new(Vec::new())
1174     };
1175
1176     if has_env {
1177         fcx.llenv = Some(unsafe {
1178             llvm::LLVMGetParam(fcx.llfn, fcx.env_arg_pos() as c_uint)
1179         });
1180     }
1181
1182     fcx
1183 }
1184
1185 /// Performs setup on a newly created function, creating the entry scope block
1186 /// and allocating space for the return pointer.
1187 pub fn init_function<'a>(fcx: &'a FunctionContext<'a>,
1188                          skip_retptr: bool,
1189                          output_type: ty::t) {
1190     let entry_bcx = fcx.new_temp_block("entry-block");
1191
1192     *fcx.entry_bcx.borrow_mut() = Some(entry_bcx);
1193
1194     // Use a dummy instruction as the insertion point for all allocas.
1195     // This is later removed in FunctionContext::cleanup.
1196     fcx.alloca_insert_pt.set(Some(unsafe {
1197         Load(entry_bcx, C_null(Type::i8p(fcx.ccx)));
1198         llvm::LLVMGetFirstInstruction(entry_bcx.llbb)
1199     }));
1200
1201     // This shouldn't need to recompute the return type,
1202     // as new_fn_ctxt did it already.
1203     let substd_output_type = output_type.substp(fcx.ccx.tcx(), fcx.param_substs);
1204
1205     if !return_type_is_void(fcx.ccx, substd_output_type) {
1206         // If the function returns nil/bot, there is no real return
1207         // value, so do not set `llretptr`.
1208         if !skip_retptr || fcx.caller_expects_out_pointer {
1209             // Otherwise, we normally allocate the llretptr, unless we
1210             // have been instructed to skip it for immediate return
1211             // values.
1212             fcx.llretptr.set(Some(make_return_pointer(fcx, substd_output_type)));
1213         }
1214     }
1215 }
1216
1217 // NB: must keep 4 fns in sync:
1218 //
1219 //  - type_of_fn
1220 //  - create_datums_for_fn_args.
1221 //  - new_fn_ctxt
1222 //  - trans_args
1223
1224 fn arg_kind(cx: &FunctionContext, t: ty::t) -> datum::Rvalue {
1225     use middle::trans::datum::{ByRef, ByValue};
1226
1227     datum::Rvalue {
1228         mode: if arg_is_indirect(cx.ccx, t) { ByRef } else { ByValue }
1229     }
1230 }
1231
1232 // work around bizarre resolve errors
1233 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
1234 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
1235
1236 // create_datums_for_fn_args: creates rvalue datums for each of the
1237 // incoming function arguments. These will later be stored into
1238 // appropriate lvalue datums.
1239 pub fn create_datums_for_fn_args(fcx: &FunctionContext,
1240                                  arg_tys: &[ty::t])
1241                                  -> Vec<RvalueDatum> {
1242     let _icx = push_ctxt("create_datums_for_fn_args");
1243
1244     // Return an array wrapping the ValueRefs that we get from
1245     // llvm::LLVMGetParam for each argument into datums.
1246     arg_tys.iter().enumerate().map(|(i, &arg_ty)| {
1247         let llarg = unsafe {
1248             llvm::LLVMGetParam(fcx.llfn, fcx.arg_pos(i) as c_uint)
1249         };
1250         datum::Datum(llarg, arg_ty, arg_kind(fcx, arg_ty))
1251     }).collect()
1252 }
1253
1254 fn copy_args_to_allocas<'a>(fcx: &FunctionContext<'a>,
1255                             arg_scope: cleanup::CustomScopeIndex,
1256                             bcx: &'a Block<'a>,
1257                             args: &[ast::Arg],
1258                             arg_datums: Vec<RvalueDatum> )
1259                             -> &'a Block<'a> {
1260     debug!("copy_args_to_allocas");
1261
1262     let _icx = push_ctxt("copy_args_to_allocas");
1263     let mut bcx = bcx;
1264
1265     let arg_scope_id = cleanup::CustomScope(arg_scope);
1266
1267     for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1268         // For certain mode/type combinations, the raw llarg values are passed
1269         // by value.  However, within the fn body itself, we want to always
1270         // have all locals and arguments be by-ref so that we can cancel the
1271         // cleanup and for better interaction with LLVM's debug info.  So, if
1272         // the argument would be passed by value, we store it into an alloca.
1273         // This alloca should be optimized away by LLVM's mem-to-reg pass in
1274         // the event it's not truly needed.
1275
1276         bcx = _match::store_arg(bcx, args[i].pat, arg_datum, arg_scope_id);
1277
1278         if fcx.ccx.sess().opts.debuginfo == FullDebugInfo {
1279             debuginfo::create_argument_metadata(bcx, &args[i]);
1280         }
1281     }
1282
1283     bcx
1284 }
1285
1286 // Ties up the llstaticallocas -> llloadenv -> lltop edges,
1287 // and builds the return block.
1288 pub fn finish_fn<'a>(fcx: &'a FunctionContext<'a>,
1289                      last_bcx: &'a Block<'a>) {
1290     let _icx = push_ctxt("finish_fn");
1291
1292     let ret_cx = match fcx.llreturn.get() {
1293         Some(llreturn) => {
1294             if !last_bcx.terminated.get() {
1295                 Br(last_bcx, llreturn);
1296             }
1297             raw_block(fcx, false, llreturn)
1298         }
1299         None => last_bcx
1300     };
1301     build_return_block(fcx, ret_cx);
1302     debuginfo::clear_source_location(fcx);
1303     fcx.cleanup();
1304 }
1305
1306 // Builds the return block for a function.
1307 pub fn build_return_block(fcx: &FunctionContext, ret_cx: &Block) {
1308     // Return the value if this function immediate; otherwise, return void.
1309     if fcx.llretptr.get().is_none() || fcx.caller_expects_out_pointer {
1310         return RetVoid(ret_cx);
1311     }
1312
1313     let retptr = Value(fcx.llretptr.get().unwrap());
1314     let retval = match retptr.get_dominating_store(ret_cx) {
1315         // If there's only a single store to the ret slot, we can directly return
1316         // the value that was stored and omit the store and the alloca
1317         Some(s) => {
1318             let retval = s.get_operand(0).unwrap().get();
1319             s.erase_from_parent();
1320
1321             if retptr.has_no_uses() {
1322                 retptr.erase_from_parent();
1323             }
1324
1325             retval
1326         }
1327         // Otherwise, load the return value from the ret slot
1328         None => Load(ret_cx, fcx.llretptr.get().unwrap())
1329     };
1330
1331
1332     Ret(ret_cx, retval);
1333 }
1334
1335 // trans_closure: Builds an LLVM function out of a source function.
1336 // If the function closes over its environment a closure will be
1337 // returned.
1338 pub fn trans_closure(ccx: &CrateContext,
1339                      decl: &ast::FnDecl,
1340                      body: &ast::Block,
1341                      llfndecl: ValueRef,
1342                      param_substs: Option<&param_substs>,
1343                      id: ast::NodeId,
1344                      _attributes: &[ast::Attribute],
1345                      output_type: ty::t,
1346                      maybe_load_env: <'a> |&'a Block<'a>| -> &'a Block<'a>) {
1347     ccx.stats.n_closures.set(ccx.stats.n_closures.get() + 1);
1348
1349     let _icx = push_ctxt("trans_closure");
1350     set_uwtable(llfndecl);
1351
1352     debug!("trans_closure(..., param_substs={})",
1353            param_substs.map(|s| s.repr(ccx.tcx())));
1354
1355     let has_env = match ty::get(ty::node_id_to_type(ccx.tcx(), id)).sty {
1356         ty::ty_closure(_) => true,
1357         _ => false
1358     };
1359
1360     let arena = TypedArena::new();
1361     let fcx = new_fn_ctxt(ccx,
1362                           llfndecl,
1363                           id,
1364                           has_env,
1365                           output_type,
1366                           param_substs.map(|s| &*s),
1367                           Some(body.span),
1368                           &arena);
1369     init_function(&fcx, false, output_type);
1370
1371     // cleanup scope for the incoming arguments
1372     let arg_scope = fcx.push_custom_cleanup_scope();
1373
1374     // Create the first basic block in the function and keep a handle on it to
1375     //  pass to finish_fn later.
1376     let bcx_top = fcx.entry_bcx.borrow().clone().unwrap();
1377     let mut bcx = bcx_top;
1378     let block_ty = node_id_type(bcx, body.id);
1379
1380     // Set up arguments to the function.
1381     let arg_tys = ty::ty_fn_args(node_id_type(bcx, id));
1382     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1383
1384     bcx = copy_args_to_allocas(&fcx,
1385                                arg_scope,
1386                                bcx,
1387                                decl.inputs.as_slice(),
1388                                arg_datums);
1389
1390     bcx = maybe_load_env(bcx);
1391
1392     // Up until here, IR instructions for this function have explicitly not been annotated with
1393     // source code location, so we don't step into call setup code. From here on, source location
1394     // emitting should be enabled.
1395     debuginfo::start_emitting_source_locations(&fcx);
1396
1397     let dest = match fcx.llretptr.get() {
1398         Some(e) => {expr::SaveIn(e)}
1399         None => {
1400             assert!(type_is_zero_size(bcx.ccx(), block_ty))
1401             expr::Ignore
1402         }
1403     };
1404
1405     // This call to trans_block is the place where we bridge between
1406     // translation calls that don't have a return value (trans_crate,
1407     // trans_mod, trans_item, et cetera) and those that do
1408     // (trans_block, trans_expr, et cetera).
1409     bcx = controlflow::trans_block(bcx, body, dest);
1410
1411     match fcx.llreturn.get() {
1412         Some(_) => {
1413             Br(bcx, fcx.return_exit_block());
1414             fcx.pop_custom_cleanup_scope(arg_scope);
1415         }
1416         None => {
1417             // Microoptimization writ large: avoid creating a separate
1418             // llreturn basic block
1419             bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_scope);
1420         }
1421     };
1422
1423     // Put return block after all other blocks.
1424     // This somewhat improves single-stepping experience in debugger.
1425     unsafe {
1426         let llreturn = fcx.llreturn.get();
1427         for &llreturn in llreturn.iter() {
1428             llvm::LLVMMoveBasicBlockAfter(llreturn, bcx.llbb);
1429         }
1430     }
1431
1432     // Insert the mandatory first few basic blocks before lltop.
1433     finish_fn(&fcx, bcx);
1434 }
1435
1436 // trans_fn: creates an LLVM function corresponding to a source language
1437 // function.
1438 pub fn trans_fn(ccx: &CrateContext,
1439                 decl: &ast::FnDecl,
1440                 body: &ast::Block,
1441                 llfndecl: ValueRef,
1442                 param_substs: Option<&param_substs>,
1443                 id: ast::NodeId,
1444                 attrs: &[ast::Attribute]) {
1445     let _s = StatRecorder::new(ccx, ccx.tcx.map.path_to_str(id).to_owned());
1446     debug!("trans_fn(param_substs={})", param_substs.map(|s| s.repr(ccx.tcx())));
1447     let _icx = push_ctxt("trans_fn");
1448     let output_type = ty::ty_fn_ret(ty::node_id_to_type(ccx.tcx(), id));
1449     trans_closure(ccx, decl, body, llfndecl,
1450                   param_substs, id, attrs, output_type, |bcx| bcx);
1451 }
1452
1453 pub fn trans_enum_variant(ccx: &CrateContext,
1454                           _enum_id: ast::NodeId,
1455                           variant: &ast::Variant,
1456                           _args: &[ast::VariantArg],
1457                           disr: ty::Disr,
1458                           param_substs: Option<&param_substs>,
1459                           llfndecl: ValueRef) {
1460     let _icx = push_ctxt("trans_enum_variant");
1461
1462     trans_enum_variant_or_tuple_like_struct(
1463         ccx,
1464         variant.node.id,
1465         disr,
1466         param_substs,
1467         llfndecl);
1468 }
1469
1470 pub fn trans_tuple_struct(ccx: &CrateContext,
1471                           _fields: &[ast::StructField],
1472                           ctor_id: ast::NodeId,
1473                           param_substs: Option<&param_substs>,
1474                           llfndecl: ValueRef) {
1475     let _icx = push_ctxt("trans_tuple_struct");
1476
1477     trans_enum_variant_or_tuple_like_struct(
1478         ccx,
1479         ctor_id,
1480         0,
1481         param_substs,
1482         llfndecl);
1483 }
1484
1485 fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
1486                                            ctor_id: ast::NodeId,
1487                                            disr: ty::Disr,
1488                                            param_substs: Option<&param_substs>,
1489                                            llfndecl: ValueRef) {
1490     let ctor_ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
1491     let ctor_ty = ctor_ty.substp(ccx.tcx(), param_substs);
1492
1493     let result_ty = match ty::get(ctor_ty).sty {
1494         ty::ty_bare_fn(ref bft) => bft.sig.output,
1495         _ => ccx.sess().bug(
1496             format!("trans_enum_variant_or_tuple_like_struct: \
1497                   unexpected ctor return type {}",
1498                  ty_to_str(ccx.tcx(), ctor_ty)))
1499     };
1500
1501     let arena = TypedArena::new();
1502     let fcx = new_fn_ctxt(ccx, llfndecl, ctor_id, false, result_ty,
1503                           param_substs.map(|s| &*s), None, &arena);
1504     init_function(&fcx, false, result_ty);
1505
1506     let arg_tys = ty::ty_fn_args(ctor_ty);
1507
1508     let arg_datums = create_datums_for_fn_args(&fcx, arg_tys.as_slice());
1509
1510     let bcx = fcx.entry_bcx.borrow().clone().unwrap();
1511
1512     if !type_is_zero_size(fcx.ccx, result_ty) {
1513         let repr = adt::represent_type(ccx, result_ty);
1514         adt::trans_start_init(bcx, &*repr, fcx.llretptr.get().unwrap(), disr);
1515         for (i, arg_datum) in arg_datums.move_iter().enumerate() {
1516             let lldestptr = adt::trans_field_ptr(bcx,
1517                                                  &*repr,
1518                                                  fcx.llretptr.get().unwrap(),
1519                                                  disr,
1520                                                  i);
1521             arg_datum.store_to(bcx, lldestptr);
1522         }
1523     }
1524
1525     finish_fn(&fcx, bcx);
1526 }
1527
1528 fn trans_enum_def(ccx: &CrateContext, enum_definition: &ast::EnumDef,
1529                   id: ast::NodeId, vi: &[Rc<ty::VariantInfo>],
1530                   i: &mut uint) {
1531     for &variant in enum_definition.variants.iter() {
1532         let disr_val = vi[*i].disr_val;
1533         *i += 1;
1534
1535         match variant.node.kind {
1536             ast::TupleVariantKind(ref args) if args.len() > 0 => {
1537                 let llfn = get_item_val(ccx, variant.node.id);
1538                 trans_enum_variant(ccx, id, variant, args.as_slice(),
1539                                    disr_val, None, llfn);
1540             }
1541             ast::TupleVariantKind(_) => {
1542                 // Nothing to do.
1543             }
1544             ast::StructVariantKind(struct_def) => {
1545                 trans_struct_def(ccx, struct_def);
1546             }
1547         }
1548     }
1549 }
1550
1551 pub struct TransItemVisitor<'a> {
1552     pub ccx: &'a CrateContext,
1553 }
1554
1555 impl<'a> Visitor<()> for TransItemVisitor<'a> {
1556     fn visit_item(&mut self, i: &ast::Item, _:()) {
1557         trans_item(self.ccx, i);
1558     }
1559 }
1560
1561 pub fn trans_item(ccx: &CrateContext, item: &ast::Item) {
1562     let _icx = push_ctxt("trans_item");
1563     match item.node {
1564       ast::ItemFn(decl, _fn_style, abi, ref generics, body) => {
1565         if abi != Rust  {
1566             let llfndecl = get_item_val(ccx, item.id);
1567             foreign::trans_rust_fn_with_foreign_abi(
1568                 ccx, decl, body, item.attrs.as_slice(), llfndecl, item.id);
1569         } else if !generics.is_type_parameterized() {
1570             let llfn = get_item_val(ccx, item.id);
1571             trans_fn(ccx,
1572                      decl,
1573                      body,
1574                      llfn,
1575                      None,
1576                      item.id,
1577                      item.attrs.as_slice());
1578         } else {
1579             // Be sure to travel more than just one layer deep to catch nested
1580             // items in blocks and such.
1581             let mut v = TransItemVisitor{ ccx: ccx };
1582             v.visit_block(body, ());
1583         }
1584       }
1585       ast::ItemImpl(ref generics, _, _, ref ms) => {
1586         meth::trans_impl(ccx, item.ident, ms.as_slice(), generics, item.id);
1587       }
1588       ast::ItemMod(ref m) => {
1589         trans_mod(ccx, m);
1590       }
1591       ast::ItemEnum(ref enum_definition, ref generics) => {
1592         if !generics.is_type_parameterized() {
1593             let vi = ty::enum_variants(ccx.tcx(), local_def(item.id));
1594             let mut i = 0;
1595             trans_enum_def(ccx, enum_definition, item.id, vi.as_slice(), &mut i);
1596         }
1597       }
1598       ast::ItemStatic(_, m, expr) => {
1599           consts::trans_const(ccx, m, item.id);
1600           // Do static_assert checking. It can't really be done much earlier
1601           // because we need to get the value of the bool out of LLVM
1602           if attr::contains_name(item.attrs.as_slice(), "static_assert") {
1603               if m == ast::MutMutable {
1604                   ccx.sess().span_fatal(expr.span,
1605                                         "cannot have static_assert on a mutable \
1606                                          static");
1607               }
1608
1609               let v = ccx.const_values.borrow().get_copy(&item.id);
1610               unsafe {
1611                   if !(llvm::LLVMConstIntGetZExtValue(v) != 0) {
1612                       ccx.sess().span_fatal(expr.span, "static assertion failed");
1613                   }
1614               }
1615           }
1616       },
1617       ast::ItemForeignMod(ref foreign_mod) => {
1618         foreign::trans_foreign_mod(ccx, foreign_mod);
1619       }
1620       ast::ItemStruct(struct_def, ref generics) => {
1621         if !generics.is_type_parameterized() {
1622             trans_struct_def(ccx, struct_def);
1623         }
1624       }
1625       ast::ItemTrait(..) => {
1626         // Inside of this trait definition, we won't be actually translating any
1627         // functions, but the trait still needs to be walked. Otherwise default
1628         // methods with items will not get translated and will cause ICE's when
1629         // metadata time comes around.
1630         let mut v = TransItemVisitor{ ccx: ccx };
1631         visit::walk_item(&mut v, item, ());
1632       }
1633       _ => {/* fall through */ }
1634     }
1635 }
1636
1637 pub fn trans_struct_def(ccx: &CrateContext, struct_def: @ast::StructDef) {
1638     // If this is a tuple-like struct, translate the constructor.
1639     match struct_def.ctor_id {
1640         // We only need to translate a constructor if there are fields;
1641         // otherwise this is a unit-like struct.
1642         Some(ctor_id) if struct_def.fields.len() > 0 => {
1643             let llfndecl = get_item_val(ccx, ctor_id);
1644             trans_tuple_struct(ccx, struct_def.fields.as_slice(),
1645                                ctor_id, None, llfndecl);
1646         }
1647         Some(_) | None => {}
1648     }
1649 }
1650
1651 // Translate a module. Doing this amounts to translating the items in the
1652 // module; there ends up being no artifact (aside from linkage names) of
1653 // separate modules in the compiled program.  That's because modules exist
1654 // only as a convenience for humans working with the code, to organize names
1655 // and control visibility.
1656 pub fn trans_mod(ccx: &CrateContext, m: &ast::Mod) {
1657     let _icx = push_ctxt("trans_mod");
1658     for item in m.items.iter() {
1659         trans_item(ccx, *item);
1660     }
1661 }
1662
1663 fn finish_register_fn(ccx: &CrateContext, sp: Span, sym: ~str, node_id: ast::NodeId,
1664                       llfn: ValueRef) {
1665     ccx.item_symbols.borrow_mut().insert(node_id, sym);
1666
1667     if !ccx.reachable.contains(&node_id) {
1668         lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
1669     }
1670
1671     if is_entry_fn(ccx.sess(), node_id) {
1672         create_entry_wrapper(ccx, sp, llfn);
1673     }
1674 }
1675
1676 fn register_fn(ccx: &CrateContext,
1677                sp: Span,
1678                sym: ~str,
1679                node_id: ast::NodeId,
1680                node_type: ty::t)
1681                -> ValueRef {
1682     let f = match ty::get(node_type).sty {
1683         ty::ty_bare_fn(ref f) => {
1684             assert!(f.abi == Rust || f.abi == RustIntrinsic);
1685             f
1686         }
1687         _ => fail!("expected bare rust fn or an intrinsic")
1688     };
1689
1690     let llfn = decl_rust_fn(ccx,
1691                             false,
1692                             f.sig.inputs.as_slice(),
1693                             f.sig.output,
1694                             sym);
1695     finish_register_fn(ccx, sp, sym, node_id, llfn);
1696     llfn
1697 }
1698
1699 // only use this for foreign function ABIs and glue, use `register_fn` for Rust functions
1700 pub fn register_fn_llvmty(ccx: &CrateContext,
1701                           sp: Span,
1702                           sym: ~str,
1703                           node_id: ast::NodeId,
1704                           cc: lib::llvm::CallConv,
1705                           fn_ty: Type,
1706                           output: ty::t) -> ValueRef {
1707     debug!("register_fn_llvmty id={} sym={}", node_id, sym);
1708
1709     let llfn = decl_fn(ccx.llmod, sym, cc, fn_ty, output);
1710     finish_register_fn(ccx, sp, sym, node_id, llfn);
1711     llfn
1712 }
1713
1714 pub fn is_entry_fn(sess: &Session, node_id: ast::NodeId) -> bool {
1715     match *sess.entry_fn.borrow() {
1716         Some((entry_id, _)) => node_id == entry_id,
1717         None => false
1718     }
1719 }
1720
1721 // Create a _rust_main(args: ~[str]) function which will be called from the
1722 // runtime rust_start function
1723 pub fn create_entry_wrapper(ccx: &CrateContext,
1724                            _sp: Span,
1725                            main_llfn: ValueRef) {
1726     let et = ccx.sess().entry_type.get().unwrap();
1727     match et {
1728         session::EntryMain => {
1729             create_entry_fn(ccx, main_llfn, true);
1730         }
1731         session::EntryStart => create_entry_fn(ccx, main_llfn, false),
1732         session::EntryNone => {}    // Do nothing.
1733     }
1734
1735     fn create_entry_fn(ccx: &CrateContext,
1736                        rust_main: ValueRef,
1737                        use_start_lang_item: bool) {
1738         let llfty = Type::func([ccx.int_type, Type::i8p(ccx).ptr_to()],
1739                                &ccx.int_type);
1740
1741         let llfn = decl_cdecl_fn(ccx.llmod, "main", llfty, ty::mk_nil());
1742         let llbb = "top".with_c_str(|buf| {
1743             unsafe {
1744                 llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llfn, buf)
1745             }
1746         });
1747         let bld = ccx.builder.b;
1748         unsafe {
1749             llvm::LLVMPositionBuilderAtEnd(bld, llbb);
1750
1751             let (start_fn, args) = if use_start_lang_item {
1752                 let start_def_id = match ccx.tcx.lang_items.require(StartFnLangItem) {
1753                     Ok(id) => id,
1754                     Err(s) => { ccx.sess().fatal(s); }
1755                 };
1756                 let start_fn = if start_def_id.krate == ast::LOCAL_CRATE {
1757                     get_item_val(ccx, start_def_id.node)
1758                 } else {
1759                     let start_fn_type = csearch::get_type(ccx.tcx(),
1760                                                           start_def_id).ty;
1761                     trans_external_path(ccx, start_def_id, start_fn_type)
1762                 };
1763
1764                 let args = {
1765                     let opaque_rust_main = "rust_main".with_c_str(|buf| {
1766                         llvm::LLVMBuildPointerCast(bld, rust_main, Type::i8p(ccx).to_ref(), buf)
1767                     });
1768
1769                     vec!(
1770                         opaque_rust_main,
1771                         llvm::LLVMGetParam(llfn, 0),
1772                         llvm::LLVMGetParam(llfn, 1)
1773                      )
1774                 };
1775                 (start_fn, args)
1776             } else {
1777                 debug!("using user-defined start fn");
1778                 let args = vec!(
1779                     llvm::LLVMGetParam(llfn, 0 as c_uint),
1780                     llvm::LLVMGetParam(llfn, 1 as c_uint)
1781                 );
1782
1783                 (rust_main, args)
1784             };
1785
1786             let result = llvm::LLVMBuildCall(bld,
1787                                              start_fn,
1788                                              args.as_ptr(),
1789                                              args.len() as c_uint,
1790                                              noname());
1791
1792             llvm::LLVMBuildRet(bld, result);
1793         }
1794     }
1795 }
1796
1797 fn exported_name(ccx: &CrateContext, id: ast::NodeId,
1798                  ty: ty::t, attrs: &[ast::Attribute]) -> ~str {
1799     match attr::first_attr_value_str_by_name(attrs, "export_name") {
1800         // Use provided name
1801         Some(name) => name.get().to_owned(),
1802
1803         _ => ccx.tcx.map.with_path(id, |mut path| {
1804             if attr::contains_name(attrs, "no_mangle") {
1805                 // Don't mangle
1806                 path.last().unwrap().to_str()
1807             } else {
1808                 // Usual name mangling
1809                 mangle_exported_name(ccx, path, ty, id)
1810             }
1811         })
1812     }
1813 }
1814
1815 pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
1816     debug!("get_item_val(id=`{:?}`)", id);
1817
1818     match ccx.item_vals.borrow().find_copy(&id) {
1819         Some(v) => return v,
1820         None => {}
1821     }
1822
1823     let mut foreign = false;
1824     let item = ccx.tcx.map.get(id);
1825     let val = match item {
1826         ast_map::NodeItem(i) => {
1827             let ty = ty::node_id_to_type(ccx.tcx(), i.id);
1828             let sym = exported_name(ccx, id, ty, i.attrs.as_slice());
1829
1830             let v = match i.node {
1831                 ast::ItemStatic(_, _, expr) => {
1832                     // If this static came from an external crate, then
1833                     // we need to get the symbol from csearch instead of
1834                     // using the current crate's name/version
1835                     // information in the hash of the symbol
1836                     debug!("making {}", sym);
1837                     let (sym, is_local) = {
1838                         match ccx.external_srcs.borrow().find(&i.id) {
1839                             Some(&did) => {
1840                                 debug!("but found in other crate...");
1841                                 (csearch::get_symbol(&ccx.sess().cstore,
1842                                                      did), false)
1843                             }
1844                             None => (sym, true)
1845                         }
1846                     };
1847
1848                     // We need the translated value here, because for enums the
1849                     // LLVM type is not fully determined by the Rust type.
1850                     let (v, inlineable) = consts::const_expr(ccx, expr, is_local);
1851                     ccx.const_values.borrow_mut().insert(id, v);
1852                     let mut inlineable = inlineable;
1853
1854                     unsafe {
1855                         let llty = llvm::LLVMTypeOf(v);
1856                         let g = sym.with_c_str(|buf| {
1857                             llvm::LLVMAddGlobal(ccx.llmod, llty, buf)
1858                         });
1859
1860                         if !ccx.reachable.contains(&id) {
1861                             lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
1862                         }
1863
1864                         // Apply the `unnamed_addr` attribute if
1865                         // requested
1866                         if attr::contains_name(i.attrs.as_slice(),
1867                                                "address_insignificant") {
1868                             if ccx.reachable.contains(&id) {
1869                                 ccx.sess().span_bug(i.span,
1870                                     "insignificant static is reachable");
1871                             }
1872                             lib::llvm::SetUnnamedAddr(g, true);
1873
1874                             // This is a curious case where we must make
1875                             // all of these statics inlineable. If a
1876                             // global is tagged as
1877                             // address_insignificant, then LLVM won't
1878                             // coalesce globals unless they have an
1879                             // internal linkage type. This means that
1880                             // external crates cannot use this global.
1881                             // This is a problem for things like inner
1882                             // statics in generic functions, because the
1883                             // function will be inlined into another
1884                             // crate and then attempt to link to the
1885                             // static in the original crate, only to
1886                             // find that it's not there. On the other
1887                             // side of inlininig, the crates knows to
1888                             // not declare this static as
1889                             // available_externally (because it isn't)
1890                             inlineable = true;
1891                         }
1892
1893                         if attr::contains_name(i.attrs.as_slice(),
1894                                                "thread_local") {
1895                             lib::llvm::set_thread_local(g, true);
1896                         }
1897
1898                         if !inlineable {
1899                             debug!("{} not inlined", sym);
1900                             ccx.non_inlineable_statics.borrow_mut()
1901                                                       .insert(id);
1902                         }
1903
1904                         ccx.item_symbols.borrow_mut().insert(i.id, sym);
1905                         g
1906                     }
1907                 }
1908
1909                 ast::ItemFn(_, _, abi, _, _) => {
1910                     let llfn = if abi == Rust {
1911                         register_fn(ccx, i.span, sym, i.id, ty)
1912                     } else {
1913                         foreign::register_rust_fn_with_foreign_abi(ccx,
1914                                                                    i.span,
1915                                                                    sym,
1916                                                                    i.id)
1917                     };
1918                     set_llvm_fn_attrs(i.attrs.as_slice(), llfn);
1919                     llfn
1920                 }
1921
1922                 _ => fail!("get_item_val: weird result in table")
1923             };
1924
1925             match attr::first_attr_value_str_by_name(i.attrs.as_slice(),
1926                                                      "link_section") {
1927                 Some(sect) => unsafe {
1928                     sect.get().with_c_str(|buf| {
1929                         llvm::LLVMSetSection(v, buf);
1930                     })
1931                 },
1932                 None => ()
1933             }
1934
1935             v
1936         }
1937
1938         ast_map::NodeTraitMethod(trait_method) => {
1939             debug!("get_item_val(): processing a NodeTraitMethod");
1940             match *trait_method {
1941                 ast::Required(_) => {
1942                     ccx.sess().bug("unexpected variant: required trait method in \
1943                                    get_item_val()");
1944                 }
1945                 ast::Provided(m) => {
1946                     register_method(ccx, id, m)
1947                 }
1948             }
1949         }
1950
1951         ast_map::NodeMethod(m) => {
1952             register_method(ccx, id, m)
1953         }
1954
1955         ast_map::NodeForeignItem(ni) => {
1956             foreign = true;
1957
1958             match ni.node {
1959                 ast::ForeignItemFn(..) => {
1960                     let abi = ccx.tcx.map.get_foreign_abi(id);
1961                     foreign::register_foreign_item_fn(ccx, abi, ni)
1962                 }
1963                 ast::ForeignItemStatic(..) => {
1964                     foreign::register_static(ccx, ni)
1965                 }
1966             }
1967         }
1968
1969         ast_map::NodeVariant(ref v) => {
1970             let llfn;
1971             let args = match v.node.kind {
1972                 ast::TupleVariantKind(ref args) => args,
1973                 ast::StructVariantKind(_) => {
1974                     fail!("struct variant kind unexpected in get_item_val")
1975                 }
1976             };
1977             assert!(args.len() != 0u);
1978             let ty = ty::node_id_to_type(ccx.tcx(), id);
1979             let parent = ccx.tcx.map.get_parent(id);
1980             let enm = ccx.tcx.map.expect_item(parent);
1981             let sym = exported_name(ccx,
1982                                     id,
1983                                     ty,
1984                                     enm.attrs.as_slice());
1985
1986             llfn = match enm.node {
1987                 ast::ItemEnum(_, _) => {
1988                     register_fn(ccx, (*v).span, sym, id, ty)
1989                 }
1990                 _ => fail!("NodeVariant, shouldn't happen")
1991             };
1992             set_inline_hint(llfn);
1993             llfn
1994         }
1995
1996         ast_map::NodeStructCtor(struct_def) => {
1997             // Only register the constructor if this is a tuple-like struct.
1998             let ctor_id = match struct_def.ctor_id {
1999                 None => {
2000                     ccx.sess().bug("attempt to register a constructor of \
2001                                     a non-tuple-like struct")
2002                 }
2003                 Some(ctor_id) => ctor_id,
2004             };
2005             let parent = ccx.tcx.map.get_parent(id);
2006             let struct_item = ccx.tcx.map.expect_item(parent);
2007             let ty = ty::node_id_to_type(ccx.tcx(), ctor_id);
2008             let sym = exported_name(ccx,
2009                                     id,
2010                                     ty,
2011                                     struct_item.attrs
2012                                                .as_slice());
2013             let llfn = register_fn(ccx, struct_item.span,
2014                                    sym, ctor_id, ty);
2015             set_inline_hint(llfn);
2016             llfn
2017         }
2018
2019         ref variant => {
2020             ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
2021                            variant))
2022         }
2023     };
2024
2025     // foreign items (extern fns and extern statics) don't have internal
2026     // linkage b/c that doesn't quite make sense. Otherwise items can
2027     // have internal linkage if they're not reachable.
2028     if !foreign && !ccx.reachable.contains(&id) {
2029         lib::llvm::SetLinkage(val, lib::llvm::InternalLinkage);
2030     }
2031
2032     ccx.item_vals.borrow_mut().insert(id, val);
2033     val
2034 }
2035
2036 fn register_method(ccx: &CrateContext, id: ast::NodeId,
2037                    m: &ast::Method) -> ValueRef {
2038     let mty = ty::node_id_to_type(ccx.tcx(), id);
2039
2040     let sym = exported_name(ccx, id, mty, m.attrs.as_slice());
2041
2042     let llfn = register_fn(ccx, m.span, sym, id, mty);
2043     set_llvm_fn_attrs(m.attrs.as_slice(), llfn);
2044     llfn
2045 }
2046
2047 pub fn p2i(ccx: &CrateContext, v: ValueRef) -> ValueRef {
2048     unsafe {
2049         return llvm::LLVMConstPtrToInt(v, ccx.int_type.to_ref());
2050     }
2051 }
2052
2053 pub fn crate_ctxt_to_encode_parms<'r>(cx: &'r CrateContext, ie: encoder::EncodeInlinedItem<'r>)
2054     -> encoder::EncodeParams<'r> {
2055         encoder::EncodeParams {
2056             diag: cx.sess().diagnostic(),
2057             tcx: cx.tcx(),
2058             reexports2: &cx.exp_map2,
2059             item_symbols: &cx.item_symbols,
2060             non_inlineable_statics: &cx.non_inlineable_statics,
2061             link_meta: &cx.link_meta,
2062             cstore: &cx.sess().cstore,
2063             encode_inlined_item: ie,
2064         }
2065 }
2066
2067 pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
2068     use flate;
2069
2070     let any_library = cx.sess().crate_types.borrow().iter().any(|ty| {
2071         *ty != session::CrateTypeExecutable
2072     });
2073     if !any_library {
2074         return Vec::new()
2075     }
2076
2077     let encode_inlined_item: encoder::EncodeInlinedItem =
2078         |ecx, ebml_w, ii| astencode::encode_inlined_item(ecx, ebml_w, ii);
2079
2080     let encode_parms = crate_ctxt_to_encode_parms(cx, encode_inlined_item);
2081     let metadata = encoder::encode_metadata(encode_parms, krate);
2082     let compressed = Vec::from_slice(encoder::metadata_encoding_version)
2083                      .append(match flate::deflate_bytes(metadata.as_slice()) {
2084                          Some(compressed) => compressed,
2085                          None => cx.sess().fatal(format!("failed to compress metadata"))
2086                      }.as_slice());
2087     let llmeta = C_bytes(cx, compressed.as_slice());
2088     let llconst = C_struct(cx, [llmeta], false);
2089     let name = format!("rust_metadata_{}_{}_{}", cx.link_meta.crateid.name,
2090                        cx.link_meta.crateid.version_or_default(), cx.link_meta.crate_hash);
2091     let llglobal = name.with_c_str(|buf| {
2092         unsafe {
2093             llvm::LLVMAddGlobal(cx.metadata_llmod, val_ty(llconst).to_ref(), buf)
2094         }
2095     });
2096     unsafe {
2097         llvm::LLVMSetInitializer(llglobal, llconst);
2098         cx.sess().targ_cfg.target_strs.meta_sect_name.with_c_str(|buf| {
2099             llvm::LLVMSetSection(llglobal, buf)
2100         });
2101     }
2102     return metadata;
2103 }
2104
2105 pub fn trans_crate(krate: ast::Crate,
2106                    analysis: CrateAnalysis,
2107                    output: &OutputFilenames) -> (ty::ctxt, CrateTranslation) {
2108     let CrateAnalysis { ty_cx: tcx, exp_map2, reachable, .. } = analysis;
2109
2110     // Before we touch LLVM, make sure that multithreading is enabled.
2111     unsafe {
2112         use sync::one::{Once, ONCE_INIT};
2113         static mut INIT: Once = ONCE_INIT;
2114         static mut POISONED: bool = false;
2115         INIT.doit(|| {
2116             if llvm::LLVMStartMultithreaded() != 1 {
2117                 // use an extra bool to make sure that all future usage of LLVM
2118                 // cannot proceed despite the Once not running more than once.
2119                 POISONED = true;
2120             }
2121         });
2122
2123         if POISONED {
2124             tcx.sess.bug("couldn't enable multi-threaded LLVM");
2125         }
2126     }
2127
2128     let link_meta = link::build_link_meta(&krate, output.out_filestem);
2129
2130     // Append ".rs" to crate name as LLVM module identifier.
2131     //
2132     // LLVM code generator emits a ".file filename" directive
2133     // for ELF backends. Value of the "filename" is set as the
2134     // LLVM module identifier.  Due to a LLVM MC bug[1], LLVM
2135     // crashes if the module identifer is same as other symbols
2136     // such as a function name in the module.
2137     // 1. http://llvm.org/bugs/show_bug.cgi?id=11479
2138     let mut llmod_id = link_meta.crateid.name.clone();
2139     llmod_id.push_str(".rs");
2140
2141     let ccx = CrateContext::new(llmod_id.as_slice(), tcx, exp_map2,
2142                                 Sha256::new(), link_meta, reachable);
2143     {
2144         let _icx = push_ctxt("text");
2145         trans_mod(&ccx, &krate.module);
2146     }
2147
2148     glue::emit_tydescs(&ccx);
2149     if ccx.sess().opts.debuginfo != NoDebugInfo {
2150         debuginfo::finalize(&ccx);
2151     }
2152
2153     // Translate the metadata.
2154     let metadata = write_metadata(&ccx, &krate);
2155     if ccx.sess().trans_stats() {
2156         println!("--- trans stats ---");
2157         println!("n_static_tydescs: {}", ccx.stats.n_static_tydescs.get());
2158         println!("n_glues_created: {}", ccx.stats.n_glues_created.get());
2159         println!("n_null_glues: {}", ccx.stats.n_null_glues.get());
2160         println!("n_real_glues: {}", ccx.stats.n_real_glues.get());
2161
2162         println!("n_fns: {}", ccx.stats.n_fns.get());
2163         println!("n_monos: {}", ccx.stats.n_monos.get());
2164         println!("n_inlines: {}", ccx.stats.n_inlines.get());
2165         println!("n_closures: {}", ccx.stats.n_closures.get());
2166         println!("fn stats:");
2167         ccx.stats.fn_stats.borrow_mut().sort_by(|&(_, _, insns_a), &(_, _, insns_b)| {
2168             insns_b.cmp(&insns_a)
2169         });
2170         for tuple in ccx.stats.fn_stats.borrow().iter() {
2171             match *tuple {
2172                 (ref name, ms, insns) => {
2173                     println!("{} insns, {} ms, {}", insns, ms, *name);
2174                 }
2175             }
2176         }
2177     }
2178     if ccx.sess().count_llvm_insns() {
2179         for (k, v) in ccx.stats.llvm_insns.borrow().iter() {
2180             println!("{:7u} {}", *v, *k);
2181         }
2182     }
2183
2184     let llcx = ccx.llcx;
2185     let link_meta = ccx.link_meta.clone();
2186     let llmod = ccx.llmod;
2187
2188     let mut reachable: Vec<~str> = ccx.reachable.iter().filter_map(|id| {
2189         ccx.item_symbols.borrow().find(id).map(|s| s.to_owned())
2190     }).collect();
2191
2192     // Make sure that some other crucial symbols are not eliminated from the
2193     // module. This includes the main function, the crate map (used for debug
2194     // log settings and I/O), and finally the curious rust_stack_exhausted
2195     // symbol. This symbol is required for use by the libmorestack library that
2196     // we link in, so we must ensure that this symbol is not internalized (if
2197     // defined in the crate).
2198     reachable.push("main".to_owned());
2199     reachable.push("rust_stack_exhausted".to_owned());
2200
2201     // referenced from .eh_frame section on some platforms
2202     reachable.push("rust_eh_personality".to_owned());
2203     reachable.push("rust_eh_personality_catch".to_owned()); // referenced from rt/rust_try.ll
2204
2205     let metadata_module = ccx.metadata_llmod;
2206     let formats = ccx.tcx.dependency_formats.borrow().clone();
2207
2208     (ccx.tcx, CrateTranslation {
2209         context: llcx,
2210         module: llmod,
2211         link: link_meta,
2212         metadata_module: metadata_module,
2213         metadata: metadata,
2214         reachable: reachable,
2215         crate_formats: formats,
2216     })
2217 }