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