]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/common.rs
auto merge of #12573 : lbonn/rust/unrecurs, r=alexcrichton
[rust.git] / src / librustc / middle / trans / common.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 #[allow(non_camel_case_types)];
12
13 //! Code that is useful in various trans modules.
14
15 use driver::session::Session;
16 use lib::llvm::{ValueRef, BasicBlockRef, BuilderRef};
17 use lib::llvm::{True, False, Bool};
18 use lib::llvm::llvm;
19 use lib;
20 use middle::lang_items::LangItem;
21 use middle::trans::base;
22 use middle::trans::build;
23 use middle::trans::cleanup;
24 use middle::trans::datum;
25 use middle::trans::datum::{Datum, Lvalue};
26 use middle::trans::debuginfo;
27 use middle::trans::type_::Type;
28 use middle::ty::substs;
29 use middle::ty;
30 use middle::typeck;
31 use util::ppaux::Repr;
32 use util::nodemap::NodeMap;
33
34 use arena::TypedArena;
35 use collections::HashMap;
36 use std::c_str::ToCStr;
37 use std::cell::{Cell, RefCell};
38 use std::libc::{c_uint, c_longlong, c_ulonglong, c_char};
39 use std::vec_ng::Vec;
40 use syntax::ast::Ident;
41 use syntax::ast;
42 use syntax::ast_map::{PathElem, PathName};
43 use syntax::codemap::Span;
44 use syntax::parse::token::InternedString;
45 use syntax::parse::token;
46
47 pub use middle::trans::context::CrateContext;
48
49 fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
50     match ty::get(ty).sty {
51         ty::ty_struct(def_id, ref substs) => {
52             let fields = ty::struct_fields(ccx.tcx, def_id, substs);
53             fields.len() == 1 &&
54                 fields.get(0).ident.name ==
55                     token::special_idents::unnamed_field.name &&
56                 type_is_immediate(ccx, fields.get(0).mt.ty)
57         }
58         _ => false
59     }
60 }
61
62 pub fn type_is_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
63     use middle::trans::machine::llsize_of_alloc;
64     use middle::trans::type_of::sizing_type_of;
65     let tcx = ccx.tcx;
66     let simple = ty::type_is_scalar(ty) || ty::type_is_boxed(ty) ||
67         ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
68         type_is_newtype_immediate(ccx, ty) || ty::type_is_bot(ty) ||
69         ty::type_is_simd(tcx, ty);
70     if simple {
71         return true;
72     }
73     match ty::get(ty).sty {
74         ty::ty_bot => true,
75         ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) => {
76             let llty = sizing_type_of(ccx, ty);
77             llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type)
78         }
79         _ => type_is_zero_size(ccx, ty)
80     }
81 }
82
83 pub fn type_is_zero_size(ccx: &CrateContext, ty: ty::t) -> bool {
84     /*!
85      * Identify types which have size zero at runtime.
86      */
87
88     use middle::trans::machine::llsize_of_alloc;
89     use middle::trans::type_of::sizing_type_of;
90     let llty = sizing_type_of(ccx, ty);
91     llsize_of_alloc(ccx, llty) == 0
92 }
93
94 pub fn return_type_is_void(ccx: &CrateContext, ty: ty::t) -> bool {
95     /*!
96      * Identifies types which we declare to be equivalent to `void`
97      * in C for the purpose of function return types. These are
98      * `()`, bot, and uninhabited enums. Note that all such types
99      * are also zero-size, but not all zero-size types use a `void`
100      * return type (in order to aid with C ABI compatibility).
101      */
102
103     ty::type_is_nil(ty) || ty::type_is_bot(ty) || ty::type_is_empty(ccx.tcx, ty)
104 }
105
106 pub fn gensym_name(name: &str) -> PathElem {
107     PathName(token::gensym(name))
108 }
109
110 pub struct tydesc_info {
111     ty: ty::t,
112     tydesc: ValueRef,
113     size: ValueRef,
114     align: ValueRef,
115     name: ValueRef,
116     visit_glue: Cell<Option<ValueRef>>,
117 }
118
119 /*
120  * A note on nomenclature of linking: "extern", "foreign", and "upcall".
121  *
122  * An "extern" is an LLVM symbol we wind up emitting an undefined external
123  * reference to. This means "we don't have the thing in this compilation unit,
124  * please make sure you link it in at runtime". This could be a reference to
125  * C code found in a C library, or rust code found in a rust crate.
126  *
127  * Most "externs" are implicitly declared (automatically) as a result of a
128  * user declaring an extern _module_ dependency; this causes the rust driver
129  * to locate an extern crate, scan its compilation metadata, and emit extern
130  * declarations for any symbols used by the declaring crate.
131  *
132  * A "foreign" is an extern that references C (or other non-rust ABI) code.
133  * There is no metadata to scan for extern references so in these cases either
134  * a header-digester like bindgen, or manual function prototypes, have to
135  * serve as declarators. So these are usually given explicitly as prototype
136  * declarations, in rust code, with ABI attributes on them noting which ABI to
137  * link via.
138  *
139  * An "upcall" is a foreign call generated by the compiler (not corresponding
140  * to any user-written call in the code) into the runtime library, to perform
141  * some helper task such as bringing a task to life, allocating memory, etc.
142  *
143  */
144
145 pub struct NodeInfo {
146     id: ast::NodeId,
147     span: Span,
148 }
149
150 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
151     NodeInfo { id: expr.id, span: expr.span }
152 }
153
154 pub struct Stats {
155     n_static_tydescs: Cell<uint>,
156     n_glues_created: Cell<uint>,
157     n_null_glues: Cell<uint>,
158     n_real_glues: Cell<uint>,
159     n_fns: Cell<uint>,
160     n_monos: Cell<uint>,
161     n_inlines: Cell<uint>,
162     n_closures: Cell<uint>,
163     n_llvm_insns: Cell<uint>,
164     llvm_insns: RefCell<HashMap<~str, uint>>,
165     // (ident, time-in-ms, llvm-instructions)
166     fn_stats: RefCell<Vec<(~str, uint, uint)> >,
167 }
168
169 pub struct BuilderRef_res {
170     b: BuilderRef,
171 }
172
173 impl Drop for BuilderRef_res {
174     fn drop(&mut self) {
175         unsafe {
176             llvm::LLVMDisposeBuilder(self.b);
177         }
178     }
179 }
180
181 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
182     BuilderRef_res {
183         b: b
184     }
185 }
186
187 pub type ExternMap = HashMap<~str, ValueRef>;
188
189 // Here `self_ty` is the real type of the self parameter to this method. It
190 // will only be set in the case of default methods.
191 pub struct param_substs {
192     tys: Vec<ty::t> ,
193     self_ty: Option<ty::t>,
194     vtables: Option<typeck::vtable_res>,
195     self_vtables: Option<typeck::vtable_param_res>
196 }
197
198 impl param_substs {
199     pub fn validate(&self) {
200         for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); }
201         for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); }
202     }
203 }
204
205 fn param_substs_to_str(this: &param_substs, tcx: ty::ctxt) -> ~str {
206     format!("param_substs \\{tys:{}, vtables:{}\\}",
207          this.tys.repr(tcx),
208          this.vtables.repr(tcx))
209 }
210
211 impl Repr for param_substs {
212     fn repr(&self, tcx: ty::ctxt) -> ~str {
213         param_substs_to_str(self, tcx)
214     }
215 }
216
217 // work around bizarre resolve errors
218 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
219 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
220
221 // Function context.  Every LLVM function we create will have one of
222 // these.
223 pub struct FunctionContext<'a> {
224     // The ValueRef returned from a call to llvm::LLVMAddFunction; the
225     // address of the first instruction in the sequence of
226     // instructions for this function that will go in the .text
227     // section of the executable we're generating.
228     llfn: ValueRef,
229
230     // The environment argument in a closure.
231     llenv: Option<ValueRef>,
232
233     // The place to store the return value. If the return type is immediate,
234     // this is an alloca in the function. Otherwise, it's the hidden first
235     // parameter to the function. After function construction, this should
236     // always be Some.
237     llretptr: Cell<Option<ValueRef>>,
238
239     entry_bcx: RefCell<Option<&'a Block<'a>>>,
240
241     // These elements: "hoisted basic blocks" containing
242     // administrative activities that have to happen in only one place in
243     // the function, due to LLVM's quirks.
244     // A marker for the place where we want to insert the function's static
245     // allocas, so that LLVM will coalesce them into a single alloca call.
246     alloca_insert_pt: Cell<Option<ValueRef>>,
247     llreturn: Cell<Option<BasicBlockRef>>,
248
249     // The a value alloca'd for calls to upcalls.rust_personality. Used when
250     // outputting the resume instruction.
251     personality: Cell<Option<ValueRef>>,
252
253     // True if the caller expects this fn to use the out pointer to
254     // return. Either way, your code should write into llretptr, but if
255     // this value is false, llretptr will be a local alloca.
256     caller_expects_out_pointer: bool,
257
258     // Maps arguments to allocas created for them in llallocas.
259     llargs: RefCell<NodeMap<LvalueDatum>>,
260
261     // Maps the def_ids for local variables to the allocas created for
262     // them in llallocas.
263     lllocals: RefCell<NodeMap<LvalueDatum>>,
264
265     // Same as above, but for closure upvars
266     llupvars: RefCell<NodeMap<ValueRef>>,
267
268     // The NodeId of the function, or -1 if it doesn't correspond to
269     // a user-defined function.
270     id: ast::NodeId,
271
272     // If this function is being monomorphized, this contains the type
273     // substitutions used.
274     param_substs: Option<@param_substs>,
275
276     // The source span and nesting context where this function comes from, for
277     // error reporting and symbol generation.
278     span: Option<Span>,
279
280     // The arena that blocks are allocated from.
281     block_arena: &'a TypedArena<Block<'a>>,
282
283     // This function's enclosing crate context.
284     ccx: @CrateContext,
285
286     // Used and maintained by the debuginfo module.
287     debug_context: debuginfo::FunctionDebugContext,
288
289     // Cleanup scopes.
290     scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
291 }
292
293 impl<'a> FunctionContext<'a> {
294     pub fn arg_pos(&self, arg: uint) -> uint {
295         let arg = self.env_arg_pos() + arg;
296         if self.llenv.is_some() {
297             arg + 1
298         } else {
299             arg
300         }
301     }
302
303     pub fn out_arg_pos(&self) -> uint {
304         assert!(self.caller_expects_out_pointer);
305         0u
306     }
307
308     pub fn env_arg_pos(&self) -> uint {
309         if self.caller_expects_out_pointer {
310             1u
311         } else {
312             0u
313         }
314     }
315
316     pub fn cleanup(&self) {
317         unsafe {
318             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
319                                                      .get()
320                                                      .unwrap());
321         }
322         // Remove the cycle between fcx and bcx, so memory can be freed
323         self.entry_bcx.set(None);
324     }
325
326     pub fn get_llreturn(&self) -> BasicBlockRef {
327         if self.llreturn.get().is_none() {
328             self.llreturn.set(Some(base::mk_return_basic_block(self.llfn)));
329         }
330
331         self.llreturn.get().unwrap()
332     }
333
334     pub fn new_block(&'a self,
335                      is_lpad: bool,
336                      name: &str,
337                      opt_node_id: Option<ast::NodeId>)
338                      -> &'a Block<'a> {
339         unsafe {
340             let llbb = name.with_c_str(|buf| {
341                     llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
342                                                         self.llfn,
343                                                         buf)
344                 });
345             Block::new(llbb, is_lpad, opt_node_id, self)
346         }
347     }
348
349     pub fn new_id_block(&'a self,
350                         name: &str,
351                         node_id: ast::NodeId)
352                         -> &'a Block<'a> {
353         self.new_block(false, name, Some(node_id))
354     }
355
356     pub fn new_temp_block(&'a self,
357                           name: &str)
358                           -> &'a Block<'a> {
359         self.new_block(false, name, None)
360     }
361
362     pub fn join_blocks(&'a self,
363                        id: ast::NodeId,
364                        in_cxs: &[&'a Block<'a>])
365                        -> &'a Block<'a> {
366         let out = self.new_id_block("join", id);
367         let mut reachable = false;
368         for bcx in in_cxs.iter() {
369             if !bcx.unreachable.get() {
370                 build::Br(*bcx, out.llbb);
371                 reachable = true;
372             }
373         }
374         if !reachable {
375             build::Unreachable(out);
376         }
377         return out;
378     }
379 }
380
381 pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
382     if !ccx.do_not_commit_warning_issued.get() {
383         ccx.do_not_commit_warning_issued.set(true);
384         ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
385     }
386 }
387
388 // Heap selectors. Indicate which heap something should go on.
389 #[deriving(Eq)]
390 pub enum heap {
391     heap_managed,
392     heap_exchange,
393     heap_exchange_closure
394 }
395
396 // Basic block context.  We create a block context for each basic block
397 // (single-entry, single-exit sequence of instructions) we generate from Rust
398 // code.  Each basic block we generate is attached to a function, typically
399 // with many basic blocks per function.  All the basic blocks attached to a
400 // function are organized as a directed graph.
401 pub struct Block<'a> {
402     // The BasicBlockRef returned from a call to
403     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
404     // block to the function pointed to by llfn.  We insert
405     // instructions into that block by way of this block context.
406     // The block pointing to this one in the function's digraph.
407     llbb: BasicBlockRef,
408     terminated: Cell<bool>,
409     unreachable: Cell<bool>,
410
411     // Is this block part of a landing pad?
412     is_lpad: bool,
413
414     // AST node-id associated with this block, if any. Used for
415     // debugging purposes only.
416     opt_node_id: Option<ast::NodeId>,
417
418     // The function context for the function to which this block is
419     // attached.
420     fcx: &'a FunctionContext<'a>,
421 }
422
423 impl<'a> Block<'a> {
424     pub fn new<'a>(
425                llbb: BasicBlockRef,
426                is_lpad: bool,
427                opt_node_id: Option<ast::NodeId>,
428                fcx: &'a FunctionContext<'a>)
429                -> &'a Block<'a> {
430         fcx.block_arena.alloc(Block {
431             llbb: llbb,
432             terminated: Cell::new(false),
433             unreachable: Cell::new(false),
434             is_lpad: is_lpad,
435             opt_node_id: opt_node_id,
436             fcx: fcx
437         })
438     }
439
440     pub fn ccx(&self) -> @CrateContext { self.fcx.ccx }
441     pub fn tcx(&self) -> ty::ctxt {
442         self.fcx.ccx.tcx
443     }
444     pub fn sess(&self) -> Session { self.fcx.ccx.sess }
445
446     pub fn ident(&self, ident: Ident) -> ~str {
447         token::get_ident(ident).get().to_str()
448     }
449
450     pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
451         self.tcx().map.node_to_str(id)
452     }
453
454     pub fn expr_to_str(&self, e: &ast::Expr) -> ~str {
455         e.repr(self.tcx())
456     }
457
458     pub fn expr_is_lval(&self, e: &ast::Expr) -> bool {
459         ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
460     }
461
462     pub fn expr_kind(&self, e: &ast::Expr) -> ty::ExprKind {
463         ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
464     }
465
466     pub fn def(&self, nid: ast::NodeId) -> ast::Def {
467         let def_map = self.tcx().def_map.borrow();
468         match def_map.get().find(&nid) {
469             Some(&v) => v,
470             None => {
471                 self.tcx().sess.bug(format!(
472                     "no def associated with node id {:?}", nid));
473             }
474         }
475     }
476
477     pub fn val_to_str(&self, val: ValueRef) -> ~str {
478         self.ccx().tn.val_to_str(val)
479     }
480
481     pub fn llty_str(&self, ty: Type) -> ~str {
482         self.ccx().tn.type_to_str(ty)
483     }
484
485     pub fn ty_to_str(&self, t: ty::t) -> ~str {
486         t.repr(self.tcx())
487     }
488
489     pub fn to_str(&self) -> ~str {
490         let blk: *Block = self;
491         format!("[block {}]", blk)
492     }
493 }
494
495 pub struct Result<'a> {
496     bcx: &'a Block<'a>,
497     val: ValueRef
498 }
499
500 pub fn rslt<'a>(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
501     Result {
502         bcx: bcx,
503         val: val,
504     }
505 }
506
507 impl<'a> Result<'a> {
508     pub fn unpack(&self, bcx: &mut &'a Block<'a>) -> ValueRef {
509         *bcx = self.bcx;
510         return self.val;
511     }
512 }
513
514 pub fn val_ty(v: ValueRef) -> Type {
515     unsafe {
516         Type::from_ref(llvm::LLVMTypeOf(v))
517     }
518 }
519
520 // LLVM constant constructors.
521 pub fn C_null(t: Type) -> ValueRef {
522     unsafe {
523         llvm::LLVMConstNull(t.to_ref())
524     }
525 }
526
527 pub fn C_undef(t: Type) -> ValueRef {
528     unsafe {
529         llvm::LLVMGetUndef(t.to_ref())
530     }
531 }
532
533 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
534     unsafe {
535         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
536     }
537 }
538
539 pub fn C_floating(s: &str, t: Type) -> ValueRef {
540     unsafe {
541         s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
542     }
543 }
544
545 pub fn C_nil() -> ValueRef {
546     C_struct([], false)
547 }
548
549 pub fn C_bool(val: bool) -> ValueRef {
550     C_integral(Type::bool(), val as u64, false)
551 }
552
553 pub fn C_i1(val: bool) -> ValueRef {
554     C_integral(Type::i1(), val as u64, false)
555 }
556
557 pub fn C_i32(i: i32) -> ValueRef {
558     return C_integral(Type::i32(), i as u64, true);
559 }
560
561 pub fn C_i64(i: i64) -> ValueRef {
562     return C_integral(Type::i64(), i as u64, true);
563 }
564
565 pub fn C_u64(i: u64) -> ValueRef {
566     return C_integral(Type::i64(), i, false);
567 }
568
569 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
570     return C_integral(cx.int_type, i as u64, true);
571 }
572
573 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
574     return C_integral(cx.int_type, i as u64, false);
575 }
576
577 pub fn C_u8(i: uint) -> ValueRef {
578     return C_integral(Type::i8(), i as u64, false);
579 }
580
581
582 // This is a 'c-like' raw string, which differs from
583 // our boxed-and-length-annotated strings.
584 pub fn C_cstr(cx: &CrateContext, s: InternedString) -> ValueRef {
585     unsafe {
586         {
587             let const_cstr_cache = cx.const_cstr_cache.borrow();
588             match const_cstr_cache.get().find(&s) {
589                 Some(&llval) => return llval,
590                 None => ()
591             }
592         }
593
594         let sc = llvm::LLVMConstStringInContext(cx.llcx,
595                                                 s.get().as_ptr() as *c_char,
596                                                 s.get().len() as c_uint,
597                                                 False);
598
599         let gsym = token::gensym("str");
600         let g = format!("str{}", gsym).with_c_str(|buf| {
601             llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
602         });
603         llvm::LLVMSetInitializer(g, sc);
604         llvm::LLVMSetGlobalConstant(g, True);
605         lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
606
607         let mut const_cstr_cache = cx.const_cstr_cache.borrow_mut();
608         const_cstr_cache.get().insert(s, g);
609         g
610     }
611 }
612
613 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
614 // you will be kicked off fast isel. See issue #4352 for an example of this.
615 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
616     unsafe {
617         let len = s.get().len();
618         let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p().to_ref());
619         C_struct([cs, C_uint(cx, len)], false)
620     }
621 }
622
623 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
624     unsafe {
625         let len = data.len();
626         let lldata = C_bytes(data);
627
628         let gsym = token::gensym("binary");
629         let g = format!("binary{}", gsym).with_c_str(|buf| {
630             llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
631         });
632         llvm::LLVMSetInitializer(g, lldata);
633         llvm::LLVMSetGlobalConstant(g, True);
634         lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
635
636         let cs = llvm::LLVMConstPointerCast(g, Type::i8p().to_ref());
637         C_struct([cs, C_uint(cx, len)], false)
638     }
639 }
640
641 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
642     unsafe {
643         let mut i = 0u;
644         let mut elts: Vec<ValueRef> = Vec::new();
645         while i < size { elts.push(C_u8(0u)); i += 1u; }
646         return llvm::LLVMConstArray(Type::i8().to_ref(),
647                                     elts.as_ptr(), elts.len() as c_uint);
648     }
649 }
650
651 pub fn C_struct(elts: &[ValueRef], packed: bool) -> ValueRef {
652     unsafe {
653
654         llvm::LLVMConstStructInContext(base::task_llcx(),
655                                        elts.as_ptr(), elts.len() as c_uint,
656                                        packed as Bool)
657     }
658 }
659
660 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
661     unsafe {
662         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
663     }
664 }
665
666 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
667     unsafe {
668         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
669     }
670 }
671
672 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
673     unsafe {
674         let ptr = bytes.as_ptr() as *c_char;
675         return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
676     }
677 }
678
679 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
680     unsafe {
681         llvm::LLVMGetParam(fndecl, param as c_uint)
682     }
683 }
684
685 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
686                   -> ValueRef {
687     unsafe {
688         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
689
690         debug!("const_get_elt(v={}, us={:?}, r={})",
691                cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
692
693         return r;
694     }
695 }
696
697 pub fn is_const(v: ValueRef) -> bool {
698     unsafe {
699         llvm::LLVMIsConstant(v) == True
700     }
701 }
702
703 pub fn const_to_int(v: ValueRef) -> c_longlong {
704     unsafe {
705         llvm::LLVMConstIntGetSExtValue(v)
706     }
707 }
708
709 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
710     unsafe {
711         llvm::LLVMConstIntGetZExtValue(v)
712     }
713 }
714
715 pub fn is_undef(val: ValueRef) -> bool {
716     unsafe {
717         llvm::LLVMIsUndef(val) != False
718     }
719 }
720
721 pub fn is_null(val: ValueRef) -> bool {
722     unsafe {
723         llvm::LLVMIsNull(val) != False
724     }
725 }
726
727 // Used to identify cached monomorphized functions and vtables
728 #[deriving(Eq, Hash)]
729 pub enum mono_param_id {
730     mono_precise(ty::t, Option<@Vec<mono_id> >),
731     mono_any,
732     mono_repr(uint /* size */,
733               uint /* align */,
734               MonoDataClass,
735               datum::RvalueMode),
736 }
737
738 #[deriving(Eq, Hash)]
739 pub enum MonoDataClass {
740     MonoBits,    // Anything not treated differently from arbitrary integer data
741     MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
742     // FIXME(#3547)---scalars and floats are
743     // treated differently in most ABIs.  But we
744     // should be doing something more detailed
745     // here.
746     MonoFloat
747 }
748
749 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
750     match ty::get(t).sty {
751         ty::ty_float(_) => MonoFloat,
752         ty::ty_rptr(..) | ty::ty_uniq(..) | ty::ty_box(..) |
753         ty::ty_str(ty::vstore_uniq) | ty::ty_vec(_, ty::vstore_uniq) |
754         ty::ty_bare_fn(..) => MonoNonNull,
755         // Is that everything?  Would closures or slices qualify?
756         _ => MonoBits
757     }
758 }
759
760 #[deriving(Eq, Hash)]
761 pub struct mono_id_ {
762     def: ast::DefId,
763     params: Vec<mono_param_id> }
764
765 pub type mono_id = @mono_id_;
766
767 pub fn umax(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
768     let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
769     return build::Select(cx, cond, b, a);
770 }
771
772 pub fn umin(cx: &Block, a: ValueRef, b: ValueRef) -> ValueRef {
773     let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
774     return build::Select(cx, cond, a, b);
775 }
776
777 pub fn align_to(cx: &Block, off: ValueRef, align: ValueRef) -> ValueRef {
778     let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
779     let bumped = build::Add(cx, off, mask);
780     return build::And(cx, bumped, build::Not(cx, mask));
781 }
782
783 pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
784     match bcx.fcx.param_substs {
785         Some(substs) => {
786             ty::subst_tps(bcx.tcx(), substs.tys.as_slice(), substs.self_ty, t)
787         }
788         _ => {
789             assert!(!ty::type_has_params(t));
790             assert!(!ty::type_has_self(t));
791             t
792         }
793     }
794 }
795
796 pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
797     let tcx = bcx.tcx();
798     let t = ty::node_id_to_type(tcx, id);
799     monomorphize_type(bcx, t)
800 }
801
802 pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t {
803     node_id_type(bcx, ex.id)
804 }
805
806 pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t {
807     let tcx = bcx.tcx();
808     let t = ty::expr_ty_adjusted(tcx, ex, bcx.ccx().maps.method_map.borrow().get());
809     monomorphize_type(bcx, t)
810 }
811
812 // Key used to lookup values supplied for type parameters in an expr.
813 #[deriving(Eq)]
814 pub enum ExprOrMethodCall {
815     // Type parameters for a path like `None::<int>`
816     ExprId(ast::NodeId),
817
818     // Type parameters for a method call like `a.foo::<int>()`
819     MethodCall(typeck::MethodCall)
820 }
821
822 pub fn node_id_type_params(bcx: &Block, node: ExprOrMethodCall) -> Vec<ty::t> {
823     let tcx = bcx.tcx();
824     let params = match node {
825         ExprId(id) => ty::node_id_to_type_params(tcx, id),
826         MethodCall(method_call) => {
827             bcx.ccx().maps.method_map.borrow().get().get(&method_call).substs.tps.clone()
828         }
829     };
830
831     if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
832         bcx.sess().bug(
833             format!("type parameters for node {:?} include inference types: {}",
834                  node, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
835     }
836
837     match bcx.fcx.param_substs {
838       Some(substs) => {
839         params.iter().map(|t| {
840             ty::subst_tps(tcx, substs.tys.as_slice(), substs.self_ty, *t)
841         }).collect()
842       }
843       _ => params
844     }
845 }
846
847 pub fn node_vtables(bcx: &Block, id: ast::NodeId)
848                  -> Option<typeck::vtable_res> {
849     let vtable_map = bcx.ccx().maps.vtable_map.borrow();
850     let raw_vtables = vtable_map.get().find(&id);
851     raw_vtables.map(|vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
852 }
853
854 // Apply the typaram substitutions in the FunctionContext to some
855 // vtables. This should eliminate any vtable_params.
856 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
857     -> typeck::vtable_res {
858     resolve_vtables_under_param_substs(fcx.ccx.tcx,
859                                        fcx.param_substs,
860                                        vts)
861 }
862
863 pub fn resolve_vtables_under_param_substs(tcx: ty::ctxt,
864                                           param_substs: Option<@param_substs>,
865                                           vts: typeck::vtable_res)
866     -> typeck::vtable_res {
867     @vts.iter().map(|ds|
868       resolve_param_vtables_under_param_substs(tcx,
869                                                param_substs,
870                                                *ds))
871         .collect()
872 }
873
874 pub fn resolve_param_vtables_under_param_substs(
875     tcx: ty::ctxt,
876     param_substs: Option<@param_substs>,
877     ds: typeck::vtable_param_res)
878     -> typeck::vtable_param_res {
879     @ds.iter().map(
880         |d| resolve_vtable_under_param_substs(tcx,
881                                               param_substs,
882                                               d))
883         .collect()
884 }
885
886
887
888 pub fn resolve_vtable_under_param_substs(tcx: ty::ctxt,
889                                          param_substs: Option<@param_substs>,
890                                          vt: &typeck::vtable_origin)
891                                          -> typeck::vtable_origin {
892     match *vt {
893         typeck::vtable_static(trait_id, ref tys, sub) => {
894             let tys = match param_substs {
895                 Some(substs) => {
896                     tys.iter().map(|t| {
897                         ty::subst_tps(tcx,
898                                       substs.tys.as_slice(),
899                                       substs.self_ty,
900                                       *t)
901                     }).collect()
902                 }
903                 _ => Vec::from_slice(tys.as_slice())
904             };
905             typeck::vtable_static(
906                 trait_id, tys,
907                 resolve_vtables_under_param_substs(tcx, param_substs, sub))
908         }
909         typeck::vtable_param(n_param, n_bound) => {
910             match param_substs {
911                 Some(substs) => {
912                     find_vtable(tcx, substs, n_param, n_bound)
913                 }
914                 _ => {
915                     tcx.sess.bug(format!(
916                         "resolve_vtable_under_param_substs: asked to lookup \
917                          but no vtables in the fn_ctxt!"))
918                 }
919             }
920         }
921     }
922 }
923
924 pub fn find_vtable(tcx: ty::ctxt,
925                    ps: &param_substs,
926                    n_param: typeck::param_index,
927                    n_bound: uint)
928                    -> typeck::vtable_origin {
929     debug!("find_vtable(n_param={:?}, n_bound={}, ps={})",
930            n_param, n_bound, ps.repr(tcx));
931
932     let param_bounds = match n_param {
933         typeck::param_self => ps.self_vtables.expect("self vtables missing"),
934         typeck::param_numbered(n) => {
935             let tables = ps.vtables
936                 .expect("vtables missing where they are needed");
937             *tables.get(n)
938         }
939     };
940     param_bounds.get(n_bound).clone()
941 }
942
943 pub fn dummy_substs(tps: Vec<ty::t> ) -> ty::substs {
944     substs {
945         regions: ty::ErasedRegions,
946         self_ty: None,
947         tps: tps
948     }
949 }
950
951 pub fn filename_and_line_num_from_span(bcx: &Block, span: Span)
952                                        -> (ValueRef, ValueRef) {
953     let loc = bcx.sess().parse_sess.cm.lookup_char_pos(span.lo);
954     let filename_cstr = C_cstr(bcx.ccx(),
955                                token::intern_and_get_ident(loc.file.name));
956     let filename = build::PointerCast(bcx, filename_cstr, Type::i8p());
957     let line = C_int(bcx.ccx(), loc.line as int);
958     (filename, line)
959 }
960
961 // Casts a Rust bool value to an i1.
962 pub fn bool_to_i1(bcx: &Block, llval: ValueRef) -> ValueRef {
963     build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(false))
964 }
965
966 pub fn langcall(bcx: &Block,
967                 span: Option<Span>,
968                 msg: &str,
969                 li: LangItem)
970                 -> ast::DefId {
971     match bcx.tcx().lang_items.require(li) {
972         Ok(id) => id,
973         Err(s) => {
974             let msg = format!("{} {}", msg, s);
975             match span {
976                 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
977                 None => { bcx.tcx().sess.fatal(msg); }
978             }
979         }
980     }
981 }