1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
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.
11 //! Code that is useful in various trans modules.
15 use driver::session::Session;
16 use lib::llvm::{ValueRef, BasicBlockRef, BuilderRef};
17 use lib::llvm::{True, False, Bool};
18 use lib::llvm::{llvm};
20 use middle::lang_items::LangItem;
21 use middle::trans::base;
22 use middle::trans::build;
23 use middle::trans::datum;
24 use middle::trans::glue;
25 use middle::trans::write_guard;
26 use middle::ty::substs;
29 use middle::borrowck::root_map_key;
30 use util::ppaux::{Repr};
32 use middle::trans::type_::Type;
34 use std::cast::transmute;
36 use std::hashmap::{HashMap};
37 use std::libc::{c_uint, c_longlong, c_ulonglong};
39 use syntax::ast::ident;
40 use syntax::ast_map::{path, path_elt};
41 use syntax::codemap::span;
42 use syntax::parse::token;
43 use syntax::{ast, ast_map};
45 pub use middle::trans::context::CrateContext;
47 pub fn gensym_name(name: &str) -> ident {
48 token::str_to_ident(fmt!("%s_%u", name, token::gensym(name)))
51 pub struct tydesc_info {
56 take_glue: Option<ValueRef>,
57 drop_glue: Option<ValueRef>,
58 free_glue: Option<ValueRef>,
59 visit_glue: Option<ValueRef>
63 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
65 * An "extern" is an LLVM symbol we wind up emitting an undefined external
66 * reference to. This means "we don't have the thing in this compilation unit,
67 * please make sure you link it in at runtime". This could be a reference to
68 * C code found in a C library, or rust code found in a rust crate.
70 * Most "externs" are implicitly declared (automatically) as a result of a
71 * user declaring an extern _module_ dependency; this causes the rust driver
72 * to locate an extern crate, scan its compilation metadata, and emit extern
73 * declarations for any symbols used by the declaring crate.
75 * A "foreign" is an extern that references C (or other non-rust ABI) code.
76 * There is no metadata to scan for extern references so in these cases either
77 * a header-digester like bindgen, or manual function prototypes, have to
78 * serve as declarators. So these are usually given explicitly as prototype
79 * declarations, in rust code, with ABI attributes on them noting which ABI to
82 * An "upcall" is a foreign call generated by the compiler (not corresponding
83 * to any user-written call in the code) into the runtime library, to perform
84 * some helper task such as bringing a task to life, allocating memory, etc.
89 n_static_tydescs: uint,
90 n_glues_created: uint,
98 llvm_insn_ctxt: ~[~str],
99 llvm_insns: HashMap<~str, uint>,
100 fn_stats: ~[(~str, uint, uint)] // (ident, time-in-ms, llvm-instructions)
103 pub struct BuilderRef_res {
107 impl Drop for BuilderRef_res {
110 llvm::LLVMDisposeBuilder(self.B);
115 pub fn BuilderRef_res(B: BuilderRef) -> BuilderRef_res {
121 pub type ExternMap = HashMap<@str, ValueRef>;
123 // Types used for llself.
124 pub struct ValSelfData {
130 // Here `self_ty` is the real type of the self parameter to this method. It
131 // will only be set in the case of default methods.
132 pub struct param_substs {
134 self_ty: Option<ty::t>,
135 vtables: Option<typeck::vtable_res>,
136 self_vtable: Option<typeck::vtable_origin>
140 pub fn validate(&self) {
141 for self.tys.iter().advance |t| { assert!(!ty::type_needs_infer(*t)); }
142 for self.self_ty.iter().advance |t| { assert!(!ty::type_needs_infer(*t)); }
146 fn param_substs_to_str(this: ¶m_substs, tcx: ty::ctxt) -> ~str {
147 fmt!("param_substs {tys:%s, vtables:%s}",
149 this.vtables.repr(tcx))
152 impl Repr for param_substs {
153 fn repr(&self, tcx: ty::ctxt) -> ~str {
154 param_substs_to_str(self, tcx)
158 // Function context. Every LLVM function we create will have one of
160 pub struct FunctionContext {
161 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
162 // address of the first instruction in the sequence of
163 // instructions for this function that will go in the .text
164 // section of the executable we're generating.
167 // The implicit environment argument that arrives in the function we're
171 // The place to store the return value. If the return type is immediate,
172 // this is an alloca in the function. Otherwise, it's the hidden first
173 // parameter to the function. After function construction, this should
175 llretptr: Option<ValueRef>,
177 entry_bcx: Option<@mut Block>,
179 // These elements: "hoisted basic blocks" containing
180 // administrative activities that have to happen in only one place in
181 // the function, due to LLVM's quirks.
182 // A marker for the place where we want to insert the function's static
183 // allocas, so that LLVM will coalesce them into a single alloca call.
184 alloca_insert_pt: Option<ValueRef>,
185 llreturn: Option<BasicBlockRef>,
186 // The 'self' value currently in use in this function, if there
189 // NB: This is the type of the self *variable*, not the self *type*. The
190 // self type is set only for default methods, while the self variable is
191 // set for all methods.
192 llself: Option<ValSelfData>,
193 // The a value alloca'd for calls to upcalls.rust_personality. Used when
194 // outputting the resume instruction.
195 personality: Option<ValueRef>,
196 // If this is a for-loop body that returns, this holds the pointers needed
197 // for that (flagptr, retptr)
198 loop_ret: Option<(ValueRef, ValueRef)>,
200 // True if this function has an immediate return value, false otherwise.
201 // If this is false, the llretptr will alias the first argument of the
203 has_immediate_return_value: bool,
205 // Maps arguments to allocas created for them in llallocas.
206 llargs: @mut HashMap<ast::node_id, ValueRef>,
207 // Maps the def_ids for local variables to the allocas created for
208 // them in llallocas.
209 lllocals: @mut HashMap<ast::node_id, ValueRef>,
210 // Same as above, but for closure upvars
211 llupvars: @mut HashMap<ast::node_id, ValueRef>,
213 // The node_id of the function, or -1 if it doesn't correspond to
214 // a user-defined function.
217 // If this function is being monomorphized, this contains the type
218 // substitutions used.
219 param_substs: Option<@param_substs>,
221 // The source span and nesting context where this function comes from, for
222 // error reporting and symbol generation.
226 // This function's enclosing crate context.
227 ccx: @mut CrateContext
230 impl FunctionContext {
231 pub fn arg_pos(&self, arg: uint) -> uint {
232 if self.has_immediate_return_value {
239 pub fn out_arg_pos(&self) -> uint {
240 assert!(self.has_immediate_return_value);
244 pub fn env_arg_pos(&self) -> uint {
245 if !self.has_immediate_return_value {
252 pub fn cleanup(&mut self) {
254 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt.get());
256 // Remove the cycle between fcx and bcx, so memory can be freed
257 self.entry_bcx = None;
260 pub fn get_llreturn(&mut self) -> BasicBlockRef {
261 if self.llreturn.is_none() {
262 self.llreturn = Some(base::mk_return_basic_block(self.llfn));
269 pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
270 if !ccx.do_not_commit_warning_issued {
271 ccx.do_not_commit_warning_issued = true;
272 ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
276 // Heap selectors. Indicate which heap something should go on.
282 heap_exchange_closure
285 #[deriving(Clone, Eq)]
288 normal_exit_and_unwind
292 clean(@fn(@mut Block) -> @mut Block, cleantype),
293 clean_temp(ValueRef, @fn(@mut Block) -> @mut Block, cleantype),
296 // Can't use deriving(Clone) because of the managed closure.
297 impl Clone for cleanup {
298 fn clone(&self) -> cleanup {
300 clean(f, ct) => clean(f, ct),
301 clean_temp(v, f, ct) => clean_temp(v, f, ct),
306 // Used to remember and reuse existing cleanup paths
307 // target: none means the path ends in an resume instruction
309 pub struct cleanup_path {
310 target: Option<BasicBlockRef>,
315 pub fn shrink_scope_clean(scope_info: &mut ScopeInfo, size: uint) {
316 scope_info.landing_pad = None;
317 scope_info.cleanup_paths = scope_info.cleanup_paths.iter()
318 .take_while(|&cu| cu.size <= size).transform(|&x|x).collect();
321 pub fn grow_scope_clean(scope_info: &mut ScopeInfo) {
322 scope_info.landing_pad = None;
325 pub fn cleanup_type(cx: ty::ctxt, ty: ty::t) -> cleantype {
326 if ty::type_needs_unwind_cleanup(cx, ty) {
327 normal_exit_and_unwind
333 pub fn add_clean(bcx: @mut Block, val: ValueRef, t: ty::t) {
334 if !ty::type_needs_drop(bcx.tcx(), t) { return; }
336 debug!("add_clean(%s, %s, %s)", bcx.to_str(), bcx.val_to_str(val), t.repr(bcx.tcx()));
338 let cleanup_type = cleanup_type(bcx.tcx(), t);
339 do in_scope_cx(bcx, None) |scope_info| {
340 scope_info.cleanups.push(clean(|a| glue::drop_ty(a, val, t), cleanup_type));
341 grow_scope_clean(scope_info);
345 pub fn add_clean_temp_immediate(cx: @mut Block, val: ValueRef, ty: ty::t) {
346 if !ty::type_needs_drop(cx.tcx(), ty) { return; }
347 debug!("add_clean_temp_immediate(%s, %s, %s)",
348 cx.to_str(), cx.val_to_str(val),
350 let cleanup_type = cleanup_type(cx.tcx(), ty);
351 do in_scope_cx(cx, None) |scope_info| {
352 scope_info.cleanups.push(
353 clean_temp(val, |a| glue::drop_ty_immediate(a, val, ty),
355 grow_scope_clean(scope_info);
359 pub fn add_clean_temp_mem(bcx: @mut Block, val: ValueRef, t: ty::t) {
360 add_clean_temp_mem_in_scope_(bcx, None, val, t);
363 pub fn add_clean_temp_mem_in_scope(bcx: @mut Block,
364 scope_id: ast::node_id,
367 add_clean_temp_mem_in_scope_(bcx, Some(scope_id), val, t);
370 pub fn add_clean_temp_mem_in_scope_(bcx: @mut Block, scope_id: Option<ast::node_id>,
371 val: ValueRef, t: ty::t) {
372 if !ty::type_needs_drop(bcx.tcx(), t) { return; }
373 debug!("add_clean_temp_mem(%s, %s, %s)",
374 bcx.to_str(), bcx.val_to_str(val),
376 let cleanup_type = cleanup_type(bcx.tcx(), t);
377 do in_scope_cx(bcx, scope_id) |scope_info| {
378 scope_info.cleanups.push(clean_temp(val, |a| glue::drop_ty(a, val, t), cleanup_type));
379 grow_scope_clean(scope_info);
382 pub fn add_clean_return_to_mut(bcx: @mut Block,
383 scope_id: ast::node_id,
384 root_key: root_map_key,
385 frozen_val_ref: ValueRef,
386 bits_val_ref: ValueRef,
387 filename_val: ValueRef,
388 line_val: ValueRef) {
389 //! When an `@mut` has been frozen, we have to
390 //! call the lang-item `return_to_mut` when the
391 //! freeze goes out of scope. We need to pass
392 //! in both the value which was frozen (`frozen_val`) and
393 //! the value (`bits_val_ref`) which was returned when the
394 //! box was frozen initially. Here, both `frozen_val_ref` and
395 //! `bits_val_ref` are in fact pointers to stack slots.
397 debug!("add_clean_return_to_mut(%s, %s, %s)",
399 bcx.val_to_str(frozen_val_ref),
400 bcx.val_to_str(bits_val_ref));
401 do in_scope_cx(bcx, Some(scope_id)) |scope_info| {
402 scope_info.cleanups.push(
405 |bcx| write_guard::return_to_mut(bcx, root_key, frozen_val_ref, bits_val_ref,
406 filename_val, line_val),
408 grow_scope_clean(scope_info);
411 pub fn add_clean_free(cx: @mut Block, ptr: ValueRef, heap: heap) {
412 let free_fn = match heap {
413 heap_managed | heap_managed_unique => {
414 let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_free(a, ptr);
417 heap_exchange | heap_exchange_closure => {
418 let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_exchange_free(a, ptr);
422 do in_scope_cx(cx, None) |scope_info| {
423 scope_info.cleanups.push(clean_temp(ptr, free_fn,
424 normal_exit_and_unwind));
425 grow_scope_clean(scope_info);
429 // Note that this only works for temporaries. We should, at some point, move
430 // to a system where we can also cancel the cleanup on local variables, but
431 // this will be more involved. For now, we simply zero out the local, and the
432 // drop glue checks whether it is zero.
433 pub fn revoke_clean(cx: @mut Block, val: ValueRef) {
434 do in_scope_cx(cx, None) |scope_info| {
435 let cleanup_pos = scope_info.cleanups.iter().position(
437 clean_temp(v, _, _) if v == val => true,
440 for cleanup_pos.iter().advance |i| {
441 scope_info.cleanups =
442 vec::append(scope_info.cleanups.slice(0u, *i).to_owned(),
443 scope_info.cleanups.slice(*i + 1u,
444 scope_info.cleanups.len()));
445 shrink_scope_clean(scope_info, *i);
450 pub fn block_cleanups(bcx: @mut Block) -> ~[cleanup] {
453 Some(inf) => inf.cleanups.clone(),
457 pub struct ScopeInfo {
458 parent: Option<@mut ScopeInfo>,
459 loop_break: Option<@mut Block>,
460 loop_label: Option<ident>,
461 // A list of functions that must be run at when leaving this
462 // block, cleaning up any variables that were introduced in the
464 cleanups: ~[cleanup],
465 // Existing cleanup paths that may be reused, indexed by destination and
466 // cleared when the set of cleanups changes.
467 cleanup_paths: ~[cleanup_path],
468 // Unwinding landing pad. Also cleared when cleanups change.
469 landing_pad: Option<BasicBlockRef>,
470 // info about the AST node this scope originated from, if any
471 node_info: Option<NodeInfo>,
475 pub fn empty_cleanups(&mut self) -> bool {
476 self.cleanups.is_empty()
480 pub trait get_node_info {
481 fn info(&self) -> Option<NodeInfo>;
484 impl get_node_info for ast::expr {
485 fn info(&self) -> Option<NodeInfo> {
486 Some(NodeInfo {id: self.id,
487 callee_id: self.get_callee_id(),
492 impl get_node_info for ast::Block {
493 fn info(&self) -> Option<NodeInfo> {
494 Some(NodeInfo {id: self.id,
500 impl get_node_info for Option<@ast::expr> {
501 fn info(&self) -> Option<NodeInfo> {
502 self.chain_ref(|s| s.info())
506 pub struct NodeInfo {
508 callee_id: Option<ast::node_id>,
512 // Basic block context. We create a block context for each basic block
513 // (single-entry, single-exit sequence of instructions) we generate from Rust
514 // code. Each basic block we generate is attached to a function, typically
515 // with many basic blocks per function. All the basic blocks attached to a
516 // function are organized as a directed graph.
518 // The BasicBlockRef returned from a call to
519 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
520 // block to the function pointed to by llfn. We insert
521 // instructions into that block by way of this block context.
522 // The block pointing to this one in the function's digraph.
526 parent: Option<@mut Block>,
527 // The current scope within this basic block
528 scope: Option<@mut ScopeInfo>,
529 // Is this block part of a landing pad?
531 // info about the AST node this block originated from, if any
532 node_info: Option<NodeInfo>,
533 // The function context for the function to which this block is
535 fcx: @mut FunctionContext
540 pub fn new(llbb: BasicBlockRef,
541 parent: Option<@mut Block>,
543 node_info: Option<NodeInfo>,
544 fcx: @mut FunctionContext)
553 node_info: node_info,
558 pub fn ccx(&self) -> @mut CrateContext { self.fcx.ccx }
559 pub fn tcx(&self) -> ty::ctxt { self.fcx.ccx.tcx }
560 pub fn sess(&self) -> Session { self.fcx.ccx.sess }
562 pub fn ident(&self, ident: ident) -> @str {
563 token::ident_to_str(&ident)
566 pub fn node_id_to_str(&self, id: ast::node_id) -> ~str {
567 ast_map::node_id_to_str(self.tcx().items, id, self.sess().intr())
570 pub fn expr_to_str(&self, e: @ast::expr) -> ~str {
574 pub fn expr_is_lval(&self, e: &ast::expr) -> bool {
575 ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
578 pub fn expr_kind(&self, e: &ast::expr) -> ty::ExprKind {
579 ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
582 pub fn def(&self, nid: ast::node_id) -> ast::def {
583 match self.tcx().def_map.find(&nid) {
586 self.tcx().sess.bug(fmt!(
587 "No def associated with node id %?", nid));
592 pub fn val_to_str(&self, val: ValueRef) -> ~str {
593 self.ccx().tn.val_to_str(val)
596 pub fn llty_str(&self, ty: Type) -> ~str {
597 self.ccx().tn.type_to_str(ty)
600 pub fn ty_to_str(&self, t: ty::t) -> ~str {
604 pub fn to_str(&self) -> ~str {
606 match self.node_info {
607 Some(node_info) => fmt!("[block %d]", node_info.id),
608 None => fmt!("[block %x]", transmute(&*self)),
619 pub fn rslt(bcx: @mut Block, val: ValueRef) -> Result {
620 Result {bcx: bcx, val: val}
624 pub fn unpack(&self, bcx: &mut @mut Block) -> ValueRef {
630 pub fn val_ty(v: ValueRef) -> Type {
632 Type::from_ref(llvm::LLVMTypeOf(v))
636 pub fn in_scope_cx(cx: @mut Block, scope_id: Option<ast::node_id>, f: &fn(si: &mut ScopeInfo)) {
638 let mut cur_scope = cur.scope;
640 cur_scope = match cur_scope {
641 Some(inf) => match scope_id {
642 Some(wanted) => match inf.node_info {
643 Some(NodeInfo { id: actual, _ }) if wanted == actual => {
644 debug!("in_scope_cx: selected cur=%s (cx=%s)",
645 cur.to_str(), cx.to_str());
652 debug!("in_scope_cx: selected cur=%s (cx=%s)",
653 cur.to_str(), cx.to_str());
659 cur = block_parent(cur);
666 pub fn block_parent(cx: @mut Block) -> @mut Block {
669 None => cx.sess().bug(fmt!("block_parent called on root block %?",
675 // Let T be the content of a box @T. tuplify_box_ty(t) returns the
676 // representation of @T as a tuple (i.e., the ty::t version of what T_box()
678 pub fn tuplify_box_ty(tcx: ty::ctxt, t: ty::t) -> ty::t {
679 let ptr = ty::mk_ptr(
681 ty::mt {ty: ty::mk_i8(), mutbl: ast::m_imm}
683 return ty::mk_tup(tcx, ~[ty::mk_uint(), ty::mk_type(tcx),
689 // LLVM constant constructors.
690 pub fn C_null(t: Type) -> ValueRef {
692 llvm::LLVMConstNull(t.to_ref())
696 pub fn C_undef(t: Type) -> ValueRef {
698 llvm::LLVMGetUndef(t.to_ref())
702 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
704 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
708 pub fn C_floating(s: &str, t: Type) -> ValueRef {
710 do s.as_c_str |buf| {
711 llvm::LLVMConstRealOfString(t.to_ref(), buf)
716 pub fn C_nil() -> ValueRef {
720 pub fn C_bool(val: bool) -> ValueRef {
721 C_integral(Type::bool(), val as u64, false)
724 pub fn C_i1(val: bool) -> ValueRef {
725 C_integral(Type::i1(), val as u64, false)
728 pub fn C_i32(i: i32) -> ValueRef {
729 return C_integral(Type::i32(), i as u64, true);
732 pub fn C_i64(i: i64) -> ValueRef {
733 return C_integral(Type::i64(), i as u64, true);
736 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
737 return C_integral(cx.int_type, i as u64, true);
740 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
741 return C_integral(cx.int_type, i as u64, false);
744 pub fn C_u8(i: uint) -> ValueRef {
745 return C_integral(Type::i8(), i as u64, false);
749 // This is a 'c-like' raw string, which differs from
750 // our boxed-and-length-annotated strings.
751 pub fn C_cstr(cx: &mut CrateContext, s: @str) -> ValueRef {
753 match cx.const_cstr_cache.find_equiv(&s) {
754 Some(&llval) => return llval,
758 let sc = do s.as_c_str |buf| {
759 llvm::LLVMConstStringInContext(cx.llcx, buf, s.len() as c_uint, False)
762 let gsym = token::gensym("str");
763 let g = do fmt!("str%u", gsym).as_c_str |buf| {
764 llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
766 llvm::LLVMSetInitializer(g, sc);
767 llvm::LLVMSetGlobalConstant(g, True);
768 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
770 cx.const_cstr_cache.insert(s, g);
776 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
777 // you will be kicked off fast isel. See issue #4352 for an example of this.
778 pub fn C_estr_slice(cx: &mut CrateContext, s: @str) -> ValueRef {
781 let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p().to_ref());
782 C_struct([cs, C_uint(cx, len + 1u /* +1 for null */)])
786 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
789 let mut elts: ~[ValueRef] = ~[];
790 while i < size { elts.push(C_u8(0u)); i += 1u; }
791 return llvm::LLVMConstArray(Type::i8().to_ref(),
792 vec::raw::to_ptr(elts), elts.len() as c_uint);
796 pub fn C_struct(elts: &[ValueRef]) -> ValueRef {
798 do elts.as_imm_buf |ptr, len| {
799 llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, False)
804 pub fn C_packed_struct(elts: &[ValueRef]) -> ValueRef {
806 do elts.as_imm_buf |ptr, len| {
807 llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, True)
812 pub fn C_named_struct(T: Type, elts: &[ValueRef]) -> ValueRef {
814 do elts.as_imm_buf |ptr, len| {
815 llvm::LLVMConstNamedStruct(T.to_ref(), ptr, len as c_uint)
820 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
822 return llvm::LLVMConstArray(ty.to_ref(), vec::raw::to_ptr(elts), elts.len() as c_uint);
826 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
828 let ptr = cast::transmute(vec::raw::to_ptr(bytes));
829 return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
833 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
835 llvm::LLVMGetParam(fndecl, param as c_uint)
839 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
842 let r = do us.as_imm_buf |p, len| {
843 llvm::LLVMConstExtractValue(v, p, len as c_uint)
846 debug!("const_get_elt(v=%s, us=%?, r=%s)",
847 cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
853 pub fn const_to_int(v: ValueRef) -> c_longlong {
855 llvm::LLVMConstIntGetSExtValue(v)
859 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
861 llvm::LLVMConstIntGetZExtValue(v)
865 pub fn is_undef(val: ValueRef) -> bool {
867 llvm::LLVMIsUndef(val) != False
871 pub fn is_null(val: ValueRef) -> bool {
873 llvm::LLVMIsNull(val) != False
877 // Used to identify cached monomorphized functions and vtables
878 #[deriving(Eq,IterBytes)]
879 pub enum mono_param_id {
880 mono_precise(ty::t, Option<@~[mono_id]>),
882 mono_repr(uint /* size */,
888 #[deriving(Eq,IterBytes)]
889 pub enum MonoDataClass {
890 MonoBits, // Anything not treated differently from arbitrary integer data
891 MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
892 // FIXME(#3547)---scalars and floats are
893 // treated differently in most ABIs. But we
894 // should be doing something more detailed
899 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
900 match ty::get(t).sty {
901 ty::ty_float(_) => MonoFloat,
902 ty::ty_rptr(*) | ty::ty_uniq(*) |
903 ty::ty_box(*) | ty::ty_opaque_box(*) |
904 ty::ty_estr(ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_uniq) |
905 ty::ty_estr(ty::vstore_box) | ty::ty_evec(_, ty::vstore_box) |
906 ty::ty_bare_fn(*) => MonoNonNull,
907 // Is that everything? Would closures or slices qualify?
913 #[deriving(Eq,IterBytes)]
914 pub struct mono_id_ {
916 params: ~[mono_param_id]
919 pub type mono_id = @mono_id_;
921 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
922 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
923 return build::Select(cx, cond, b, a);
926 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
927 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
928 return build::Select(cx, cond, a, b);
931 pub fn align_to(cx: @mut Block, off: ValueRef, align: ValueRef) -> ValueRef {
932 let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
933 let bumped = build::Add(cx, off, mask);
934 return build::And(cx, bumped, build::Not(cx, mask));
937 pub fn path_str(sess: session::Session, p: &[path_elt]) -> ~str {
939 let mut first = true;
940 for p.iter().advance |e| {
942 ast_map::path_name(s) | ast_map::path_mod(s) => {
948 r.push_str(sess.str_of(s));
955 pub fn monomorphize_type(bcx: @mut Block, t: ty::t) -> ty::t {
956 match bcx.fcx.param_substs {
958 ty::subst_tps(bcx.tcx(), substs.tys, substs.self_ty, t)
961 assert!(!ty::type_has_params(t));
962 assert!(!ty::type_has_self(t));
968 pub fn node_id_type(bcx: @mut Block, id: ast::node_id) -> ty::t {
970 let t = ty::node_id_to_type(tcx, id);
971 monomorphize_type(bcx, t)
974 pub fn expr_ty(bcx: @mut Block, ex: &ast::expr) -> ty::t {
975 node_id_type(bcx, ex.id)
978 pub fn expr_ty_adjusted(bcx: @mut Block, ex: &ast::expr) -> ty::t {
980 let t = ty::expr_ty_adjusted(tcx, ex);
981 monomorphize_type(bcx, t)
984 pub fn node_id_type_params(bcx: @mut Block, id: ast::node_id) -> ~[ty::t] {
986 let params = ty::node_id_to_type_params(tcx, id);
988 if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
990 fmt!("Type parameters for node %d include inference types: %s",
991 id, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
994 match bcx.fcx.param_substs {
996 do params.iter().transform |t| {
997 ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1004 pub fn node_vtables(bcx: @mut Block, id: ast::node_id)
1005 -> Option<typeck::vtable_res> {
1006 let raw_vtables = bcx.ccx().maps.vtable_map.find(&id);
1008 |&vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
1011 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
1012 -> typeck::vtable_res {
1013 resolve_vtables_under_param_substs(fcx.ccx.tcx,
1018 pub fn resolve_vtables_under_param_substs(tcx: ty::ctxt,
1019 param_substs: Option<@param_substs>,
1020 vts: typeck::vtable_res)
1021 -> typeck::vtable_res {
1022 @vts.iter().transform(|ds|
1023 @ds.iter().transform(
1024 |d| resolve_vtable_under_param_substs(tcx,
1027 .collect::<~[typeck::vtable_origin]>())
1028 .collect::<~[typeck::vtable_param_res]>()
1032 // Apply the typaram substitutions in the FunctionContext to a vtable. This should
1033 // eliminate any vtable_params.
1034 pub fn resolve_vtable_in_fn_ctxt(fcx: &FunctionContext, vt: &typeck::vtable_origin)
1035 -> typeck::vtable_origin {
1036 resolve_vtable_under_param_substs(fcx.ccx.tcx,
1041 pub fn resolve_vtable_under_param_substs(tcx: ty::ctxt,
1042 param_substs: Option<@param_substs>,
1043 vt: &typeck::vtable_origin)
1044 -> typeck::vtable_origin {
1046 typeck::vtable_static(trait_id, ref tys, sub) => {
1047 let tys = match param_substs {
1049 do tys.iter().transform |t| {
1050 ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1055 typeck::vtable_static(
1057 resolve_vtables_under_param_substs(tcx, param_substs, sub))
1059 typeck::vtable_param(n_param, n_bound) => {
1060 match param_substs {
1062 find_vtable(tcx, substs, n_param, n_bound)
1066 "resolve_vtable_in_fn_ctxt: asked to lookup but \
1067 no vtables in the fn_ctxt!"))
1071 typeck::vtable_self(_trait_id) => {
1072 match param_substs {
1074 {self_vtable: Some(ref self_vtable), _}) => {
1075 (*self_vtable).clone()
1079 "resolve_vtable_in_fn_ctxt: asked to lookup but \
1080 no self_vtable in the fn_ctxt!"))
1087 pub fn find_vtable(tcx: ty::ctxt,
1091 -> typeck::vtable_origin {
1092 debug!("find_vtable(n_param=%u, n_bound=%u, ps=%s)",
1093 n_param, n_bound, ps.repr(tcx));
1095 ps.vtables.get()[n_param][n_bound].clone()
1098 pub fn dummy_substs(tps: ~[ty::t]) -> ty::substs {
1100 self_r: Some(ty::re_bound(ty::br_self)),
1106 pub fn filename_and_line_num_from_span(bcx: @mut Block,
1107 span: span) -> (ValueRef, ValueRef) {
1108 let loc = bcx.sess().parse_sess.cm.lookup_char_pos(span.lo);
1109 let filename_cstr = C_cstr(bcx.ccx(), loc.file.name);
1110 let filename = build::PointerCast(bcx, filename_cstr, Type::i8p());
1111 let line = C_int(bcx.ccx(), loc.line as int);
1115 // Casts a Rust bool value to an i1.
1116 pub fn bool_to_i1(bcx: @mut Block, llval: ValueRef) -> ValueRef {
1117 build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(false))
1120 pub fn langcall(bcx: @mut Block, span: Option<span>, msg: &str,
1121 li: LangItem) -> ast::def_id {
1122 match bcx.tcx().lang_items.require(li) {
1125 let msg = fmt!("%s %s", msg, s);
1127 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
1128 None => { bcx.tcx().sess.fatal(msg); }