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::c_str::ToCStr;
35 use std::cast::transmute;
37 use std::hashmap::{HashMap};
38 use std::libc::{c_uint, c_longlong, c_ulonglong};
40 use syntax::ast::ident;
41 use syntax::ast_map::{path, path_elt};
42 use syntax::codemap::span;
43 use syntax::parse::token;
44 use syntax::{ast, ast_map};
46 pub use middle::trans::context::CrateContext;
48 pub fn gensym_name(name: &str) -> ident {
49 token::str_to_ident(fmt!("%s_%u", name, token::gensym(name)))
52 pub struct tydesc_info {
57 take_glue: Option<ValueRef>,
58 drop_glue: Option<ValueRef>,
59 free_glue: Option<ValueRef>,
60 visit_glue: Option<ValueRef>
64 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
66 * An "extern" is an LLVM symbol we wind up emitting an undefined external
67 * reference to. This means "we don't have the thing in this compilation unit,
68 * please make sure you link it in at runtime". This could be a reference to
69 * C code found in a C library, or rust code found in a rust crate.
71 * Most "externs" are implicitly declared (automatically) as a result of a
72 * user declaring an extern _module_ dependency; this causes the rust driver
73 * to locate an extern crate, scan its compilation metadata, and emit extern
74 * declarations for any symbols used by the declaring crate.
76 * A "foreign" is an extern that references C (or other non-rust ABI) code.
77 * There is no metadata to scan for extern references so in these cases either
78 * a header-digester like bindgen, or manual function prototypes, have to
79 * serve as declarators. So these are usually given explicitly as prototype
80 * declarations, in rust code, with ABI attributes on them noting which ABI to
83 * An "upcall" is a foreign call generated by the compiler (not corresponding
84 * to any user-written call in the code) into the runtime library, to perform
85 * some helper task such as bringing a task to life, allocating memory, etc.
90 n_static_tydescs: uint,
91 n_glues_created: uint,
99 llvm_insn_ctxt: ~[~str],
100 llvm_insns: HashMap<~str, uint>,
101 fn_stats: ~[(~str, uint, uint)] // (ident, time-in-ms, llvm-instructions)
104 pub struct BuilderRef_res {
108 impl Drop for BuilderRef_res {
111 llvm::LLVMDisposeBuilder(self.B);
116 pub fn BuilderRef_res(B: BuilderRef) -> BuilderRef_res {
122 pub type ExternMap = HashMap<@str, ValueRef>;
124 // Types used for llself.
125 pub struct ValSelfData {
131 // Here `self_ty` is the real type of the self parameter to this method. It
132 // will only be set in the case of default methods.
133 pub struct param_substs {
135 self_ty: Option<ty::t>,
136 vtables: Option<typeck::vtable_res>,
137 self_vtables: Option<typeck::vtable_param_res>
141 pub fn validate(&self) {
142 for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); }
143 for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); }
147 fn param_substs_to_str(this: ¶m_substs, tcx: ty::ctxt) -> ~str {
148 fmt!("param_substs {tys:%s, vtables:%s}",
150 this.vtables.repr(tcx))
153 impl Repr for param_substs {
154 fn repr(&self, tcx: ty::ctxt) -> ~str {
155 param_substs_to_str(self, tcx)
159 // Function context. Every LLVM function we create will have one of
161 pub struct FunctionContext {
162 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
163 // address of the first instruction in the sequence of
164 // instructions for this function that will go in the .text
165 // section of the executable we're generating.
168 // The implicit environment argument that arrives in the function we're
172 // The place to store the return value. If the return type is immediate,
173 // this is an alloca in the function. Otherwise, it's the hidden first
174 // parameter to the function. After function construction, this should
176 llretptr: Option<ValueRef>,
178 entry_bcx: Option<@mut Block>,
180 // These elements: "hoisted basic blocks" containing
181 // administrative activities that have to happen in only one place in
182 // the function, due to LLVM's quirks.
183 // A marker for the place where we want to insert the function's static
184 // allocas, so that LLVM will coalesce them into a single alloca call.
185 alloca_insert_pt: Option<ValueRef>,
186 llreturn: Option<BasicBlockRef>,
187 // The 'self' value currently in use in this function, if there
190 // NB: This is the type of the self *variable*, not the self *type*. The
191 // self type is set only for default methods, while the self variable is
192 // set for all methods.
193 llself: Option<ValSelfData>,
194 // The a value alloca'd for calls to upcalls.rust_personality. Used when
195 // outputting the resume instruction.
196 personality: Option<ValueRef>,
197 // If this is a for-loop body that returns, this holds the pointers needed
198 // for that (flagptr, retptr)
199 loop_ret: Option<(ValueRef, ValueRef)>,
201 // True if this function has an immediate return value, false otherwise.
202 // If this is false, the llretptr will alias the first argument of the
204 has_immediate_return_value: bool,
206 // Maps arguments to allocas created for them in llallocas.
207 llargs: @mut HashMap<ast::NodeId, ValueRef>,
208 // Maps the def_ids for local variables to the allocas created for
209 // them in llallocas.
210 lllocals: @mut HashMap<ast::NodeId, ValueRef>,
211 // Same as above, but for closure upvars
212 llupvars: @mut HashMap<ast::NodeId, ValueRef>,
214 // The NodeId of the function, or -1 if it doesn't correspond to
215 // a user-defined function.
218 // If this function is being monomorphized, this contains the type
219 // substitutions used.
220 param_substs: Option<@param_substs>,
222 // The source span and nesting context where this function comes from, for
223 // error reporting and symbol generation.
227 // This function's enclosing crate context.
228 ccx: @mut CrateContext
231 impl FunctionContext {
232 pub fn arg_pos(&self, arg: uint) -> uint {
233 if self.has_immediate_return_value {
240 pub fn out_arg_pos(&self) -> uint {
241 assert!(self.has_immediate_return_value);
245 pub fn env_arg_pos(&self) -> uint {
246 if !self.has_immediate_return_value {
253 pub fn cleanup(&mut self) {
255 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt.get());
257 // Remove the cycle between fcx and bcx, so memory can be freed
258 self.entry_bcx = None;
261 pub fn get_llreturn(&mut self) -> BasicBlockRef {
262 if self.llreturn.is_none() {
263 self.llreturn = Some(base::mk_return_basic_block(self.llfn));
270 pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
271 if !ccx.do_not_commit_warning_issued {
272 ccx.do_not_commit_warning_issued = true;
273 ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
277 // Heap selectors. Indicate which heap something should go on.
283 heap_exchange_closure
286 #[deriving(Clone, Eq)]
289 normal_exit_and_unwind
293 clean(@fn(@mut Block) -> @mut Block, cleantype),
294 clean_temp(ValueRef, @fn(@mut Block) -> @mut Block, cleantype),
297 // Can't use deriving(Clone) because of the managed closure.
298 impl Clone for cleanup {
299 fn clone(&self) -> cleanup {
301 clean(f, ct) => clean(f, ct),
302 clean_temp(v, f, ct) => clean_temp(v, f, ct),
307 // Used to remember and reuse existing cleanup paths
308 // target: none means the path ends in an resume instruction
310 pub struct cleanup_path {
311 target: Option<BasicBlockRef>,
316 pub fn shrink_scope_clean(scope_info: &mut ScopeInfo, size: uint) {
317 scope_info.landing_pad = None;
318 scope_info.cleanup_paths = scope_info.cleanup_paths.iter()
319 .take_while(|&cu| cu.size <= size).transform(|&x|x).collect();
322 pub fn grow_scope_clean(scope_info: &mut ScopeInfo) {
323 scope_info.landing_pad = None;
326 pub fn cleanup_type(cx: ty::ctxt, ty: ty::t) -> cleantype {
327 if ty::type_needs_unwind_cleanup(cx, ty) {
328 normal_exit_and_unwind
334 pub fn add_clean(bcx: @mut Block, val: ValueRef, t: ty::t) {
335 if !ty::type_needs_drop(bcx.tcx(), t) { return; }
337 debug!("add_clean(%s, %s, %s)", bcx.to_str(), bcx.val_to_str(val), t.repr(bcx.tcx()));
339 let cleanup_type = cleanup_type(bcx.tcx(), t);
340 do in_scope_cx(bcx, None) |scope_info| {
341 scope_info.cleanups.push(clean(|a| glue::drop_ty(a, val, t), cleanup_type));
342 grow_scope_clean(scope_info);
346 pub fn add_clean_temp_immediate(cx: @mut Block, val: ValueRef, ty: ty::t) {
347 if !ty::type_needs_drop(cx.tcx(), ty) { return; }
348 debug!("add_clean_temp_immediate(%s, %s, %s)",
349 cx.to_str(), cx.val_to_str(val),
351 let cleanup_type = cleanup_type(cx.tcx(), ty);
352 do in_scope_cx(cx, None) |scope_info| {
353 scope_info.cleanups.push(
354 clean_temp(val, |a| glue::drop_ty_immediate(a, val, ty),
356 grow_scope_clean(scope_info);
360 pub fn add_clean_temp_mem(bcx: @mut Block, val: ValueRef, t: ty::t) {
361 add_clean_temp_mem_in_scope_(bcx, None, val, t);
364 pub fn add_clean_temp_mem_in_scope(bcx: @mut Block,
365 scope_id: ast::NodeId,
368 add_clean_temp_mem_in_scope_(bcx, Some(scope_id), val, t);
371 pub fn add_clean_temp_mem_in_scope_(bcx: @mut Block, scope_id: Option<ast::NodeId>,
372 val: ValueRef, t: ty::t) {
373 if !ty::type_needs_drop(bcx.tcx(), t) { return; }
374 debug!("add_clean_temp_mem(%s, %s, %s)",
375 bcx.to_str(), bcx.val_to_str(val),
377 let cleanup_type = cleanup_type(bcx.tcx(), t);
378 do in_scope_cx(bcx, scope_id) |scope_info| {
379 scope_info.cleanups.push(clean_temp(val, |a| glue::drop_ty(a, val, t), cleanup_type));
380 grow_scope_clean(scope_info);
383 pub fn add_clean_return_to_mut(bcx: @mut Block,
384 scope_id: ast::NodeId,
385 root_key: root_map_key,
386 frozen_val_ref: ValueRef,
387 bits_val_ref: ValueRef,
388 filename_val: ValueRef,
389 line_val: ValueRef) {
390 //! When an `@mut` has been frozen, we have to
391 //! call the lang-item `return_to_mut` when the
392 //! freeze goes out of scope. We need to pass
393 //! in both the value which was frozen (`frozen_val`) and
394 //! the value (`bits_val_ref`) which was returned when the
395 //! box was frozen initially. Here, both `frozen_val_ref` and
396 //! `bits_val_ref` are in fact pointers to stack slots.
398 debug!("add_clean_return_to_mut(%s, %s, %s)",
400 bcx.val_to_str(frozen_val_ref),
401 bcx.val_to_str(bits_val_ref));
402 do in_scope_cx(bcx, Some(scope_id)) |scope_info| {
403 scope_info.cleanups.push(
406 |bcx| write_guard::return_to_mut(bcx, root_key, frozen_val_ref, bits_val_ref,
407 filename_val, line_val),
409 grow_scope_clean(scope_info);
412 pub fn add_clean_free(cx: @mut Block, ptr: ValueRef, heap: heap) {
413 let free_fn = match heap {
414 heap_managed | heap_managed_unique => {
415 let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_free(a, ptr);
418 heap_exchange | heap_exchange_closure => {
419 let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_exchange_free(a, ptr);
423 do in_scope_cx(cx, None) |scope_info| {
424 scope_info.cleanups.push(clean_temp(ptr, free_fn,
425 normal_exit_and_unwind));
426 grow_scope_clean(scope_info);
430 // Note that this only works for temporaries. We should, at some point, move
431 // to a system where we can also cancel the cleanup on local variables, but
432 // this will be more involved. For now, we simply zero out the local, and the
433 // drop glue checks whether it is zero.
434 pub fn revoke_clean(cx: @mut Block, val: ValueRef) {
435 do in_scope_cx(cx, None) |scope_info| {
436 let cleanup_pos = scope_info.cleanups.iter().position(
438 clean_temp(v, _, _) if v == val => true,
441 for i in cleanup_pos.iter() {
442 scope_info.cleanups =
443 vec::append(scope_info.cleanups.slice(0u, *i).to_owned(),
444 scope_info.cleanups.slice(*i + 1u,
445 scope_info.cleanups.len()));
446 shrink_scope_clean(scope_info, *i);
451 pub fn block_cleanups(bcx: @mut Block) -> ~[cleanup] {
454 Some(inf) => inf.cleanups.clone(),
458 pub struct ScopeInfo {
459 parent: Option<@mut ScopeInfo>,
460 loop_break: Option<@mut Block>,
461 loop_label: Option<ident>,
462 // A list of functions that must be run at when leaving this
463 // block, cleaning up any variables that were introduced in the
465 cleanups: ~[cleanup],
466 // Existing cleanup paths that may be reused, indexed by destination and
467 // cleared when the set of cleanups changes.
468 cleanup_paths: ~[cleanup_path],
469 // Unwinding landing pad. Also cleared when cleanups change.
470 landing_pad: Option<BasicBlockRef>,
471 // info about the AST node this scope originated from, if any
472 node_info: Option<NodeInfo>,
476 pub fn empty_cleanups(&mut self) -> bool {
477 self.cleanups.is_empty()
481 pub trait get_node_info {
482 fn info(&self) -> Option<NodeInfo>;
485 impl get_node_info for ast::expr {
486 fn info(&self) -> Option<NodeInfo> {
487 Some(NodeInfo {id: self.id,
488 callee_id: self.get_callee_id(),
493 impl get_node_info for ast::Block {
494 fn info(&self) -> Option<NodeInfo> {
495 Some(NodeInfo {id: self.id,
501 impl get_node_info for Option<@ast::expr> {
502 fn info(&self) -> Option<NodeInfo> {
503 self.chain_ref(|s| s.info())
507 pub struct NodeInfo {
509 callee_id: Option<ast::NodeId>,
513 // Basic block context. We create a block context for each basic block
514 // (single-entry, single-exit sequence of instructions) we generate from Rust
515 // code. Each basic block we generate is attached to a function, typically
516 // with many basic blocks per function. All the basic blocks attached to a
517 // function are organized as a directed graph.
519 // The BasicBlockRef returned from a call to
520 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
521 // block to the function pointed to by llfn. We insert
522 // instructions into that block by way of this block context.
523 // The block pointing to this one in the function's digraph.
527 parent: Option<@mut Block>,
528 // The current scope within this basic block
529 scope: Option<@mut ScopeInfo>,
530 // Is this block part of a landing pad?
532 // info about the AST node this block originated from, if any
533 node_info: Option<NodeInfo>,
534 // The function context for the function to which this block is
536 fcx: @mut FunctionContext
541 pub fn new(llbb: BasicBlockRef,
542 parent: Option<@mut Block>,
544 node_info: Option<NodeInfo>,
545 fcx: @mut FunctionContext)
554 node_info: node_info,
559 pub fn ccx(&self) -> @mut CrateContext { self.fcx.ccx }
560 pub fn tcx(&self) -> ty::ctxt { self.fcx.ccx.tcx }
561 pub fn sess(&self) -> Session { self.fcx.ccx.sess }
563 pub fn ident(&self, ident: ident) -> @str {
564 token::ident_to_str(&ident)
567 pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
568 ast_map::node_id_to_str(self.tcx().items, id, self.sess().intr())
571 pub fn expr_to_str(&self, e: @ast::expr) -> ~str {
575 pub fn expr_is_lval(&self, e: &ast::expr) -> bool {
576 ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
579 pub fn expr_kind(&self, e: &ast::expr) -> ty::ExprKind {
580 ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
583 pub fn def(&self, nid: ast::NodeId) -> ast::def {
584 match self.tcx().def_map.find(&nid) {
587 self.tcx().sess.bug(fmt!(
588 "No def associated with node id %?", nid));
593 pub fn val_to_str(&self, val: ValueRef) -> ~str {
594 self.ccx().tn.val_to_str(val)
597 pub fn llty_str(&self, ty: Type) -> ~str {
598 self.ccx().tn.type_to_str(ty)
601 pub fn ty_to_str(&self, t: ty::t) -> ~str {
605 pub fn to_str(&self) -> ~str {
607 match self.node_info {
608 Some(node_info) => fmt!("[block %d]", node_info.id),
609 None => fmt!("[block %x]", transmute(&*self)),
620 pub fn rslt(bcx: @mut Block, val: ValueRef) -> Result {
621 Result {bcx: bcx, val: val}
625 pub fn unpack(&self, bcx: &mut @mut Block) -> ValueRef {
631 pub fn val_ty(v: ValueRef) -> Type {
633 Type::from_ref(llvm::LLVMTypeOf(v))
637 pub fn in_scope_cx(cx: @mut Block, scope_id: Option<ast::NodeId>, f: &fn(si: &mut ScopeInfo)) {
639 let mut cur_scope = cur.scope;
641 cur_scope = match cur_scope {
642 Some(inf) => match scope_id {
643 Some(wanted) => match inf.node_info {
644 Some(NodeInfo { id: actual, _ }) if wanted == actual => {
645 debug!("in_scope_cx: selected cur=%s (cx=%s)",
646 cur.to_str(), cx.to_str());
653 debug!("in_scope_cx: selected cur=%s (cx=%s)",
654 cur.to_str(), cx.to_str());
660 cur = block_parent(cur);
667 pub fn block_parent(cx: @mut Block) -> @mut Block {
670 None => cx.sess().bug(fmt!("block_parent called on root block %?",
676 // Let T be the content of a box @T. tuplify_box_ty(t) returns the
677 // representation of @T as a tuple (i.e., the ty::t version of what T_box()
679 pub fn tuplify_box_ty(tcx: ty::ctxt, t: ty::t) -> ty::t {
680 let ptr = ty::mk_ptr(
682 ty::mt {ty: ty::mk_i8(), mutbl: ast::m_imm}
684 return ty::mk_tup(tcx, ~[ty::mk_uint(), ty::mk_type(tcx),
690 // LLVM constant constructors.
691 pub fn C_null(t: Type) -> ValueRef {
693 llvm::LLVMConstNull(t.to_ref())
697 pub fn C_undef(t: Type) -> ValueRef {
699 llvm::LLVMGetUndef(t.to_ref())
703 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
705 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
709 pub fn C_floating(s: &str, t: Type) -> ValueRef {
711 do s.to_c_str().with_ref |buf| {
712 llvm::LLVMConstRealOfString(t.to_ref(), buf)
717 pub fn C_nil() -> ValueRef {
721 pub fn C_bool(val: bool) -> ValueRef {
722 C_integral(Type::bool(), val as u64, false)
725 pub fn C_i1(val: bool) -> ValueRef {
726 C_integral(Type::i1(), val as u64, false)
729 pub fn C_i32(i: i32) -> ValueRef {
730 return C_integral(Type::i32(), i as u64, true);
733 pub fn C_i64(i: i64) -> ValueRef {
734 return C_integral(Type::i64(), i as u64, true);
737 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
738 return C_integral(cx.int_type, i as u64, true);
741 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
742 return C_integral(cx.int_type, i as u64, false);
745 pub fn C_u8(i: uint) -> ValueRef {
746 return C_integral(Type::i8(), i as u64, false);
750 // This is a 'c-like' raw string, which differs from
751 // our boxed-and-length-annotated strings.
752 pub fn C_cstr(cx: &mut CrateContext, s: @str) -> ValueRef {
754 match cx.const_cstr_cache.find_equiv(&s) {
755 Some(&llval) => return llval,
759 let sc = do s.to_c_str().with_ref |buf| {
760 llvm::LLVMConstStringInContext(cx.llcx, buf, s.len() as c_uint, False)
763 let gsym = token::gensym("str");
764 let g = do fmt!("str%u", gsym).to_c_str().with_ref |buf| {
765 llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
767 llvm::LLVMSetInitializer(g, sc);
768 llvm::LLVMSetGlobalConstant(g, True);
769 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
771 cx.const_cstr_cache.insert(s, g);
777 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
778 // you will be kicked off fast isel. See issue #4352 for an example of this.
779 pub fn C_estr_slice(cx: &mut CrateContext, s: @str) -> ValueRef {
782 let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p().to_ref());
783 C_struct([cs, C_uint(cx, len)])
787 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
790 let mut elts: ~[ValueRef] = ~[];
791 while i < size { elts.push(C_u8(0u)); i += 1u; }
792 return llvm::LLVMConstArray(Type::i8().to_ref(),
793 vec::raw::to_ptr(elts), elts.len() as c_uint);
797 pub fn C_struct(elts: &[ValueRef]) -> ValueRef {
799 do elts.as_imm_buf |ptr, len| {
800 llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, False)
805 pub fn C_packed_struct(elts: &[ValueRef]) -> ValueRef {
807 do elts.as_imm_buf |ptr, len| {
808 llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, True)
813 pub fn C_named_struct(T: Type, elts: &[ValueRef]) -> ValueRef {
815 do elts.as_imm_buf |ptr, len| {
816 llvm::LLVMConstNamedStruct(T.to_ref(), ptr, len as c_uint)
821 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
823 return llvm::LLVMConstArray(ty.to_ref(), vec::raw::to_ptr(elts), elts.len() as c_uint);
827 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
829 let ptr = cast::transmute(vec::raw::to_ptr(bytes));
830 return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
834 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
836 llvm::LLVMGetParam(fndecl, param as c_uint)
840 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
843 let r = do us.as_imm_buf |p, len| {
844 llvm::LLVMConstExtractValue(v, p, len as c_uint)
847 debug!("const_get_elt(v=%s, us=%?, r=%s)",
848 cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
854 pub fn is_const(v: ValueRef) -> bool {
856 llvm::LLVMIsConstant(v) == True
860 pub fn const_to_int(v: ValueRef) -> c_longlong {
862 llvm::LLVMConstIntGetSExtValue(v)
866 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
868 llvm::LLVMConstIntGetZExtValue(v)
872 pub fn is_undef(val: ValueRef) -> bool {
874 llvm::LLVMIsUndef(val) != False
878 pub fn is_null(val: ValueRef) -> bool {
880 llvm::LLVMIsNull(val) != False
884 // Used to identify cached monomorphized functions and vtables
885 #[deriving(Eq,IterBytes)]
886 pub enum mono_param_id {
887 mono_precise(ty::t, Option<@~[mono_id]>),
889 mono_repr(uint /* size */,
895 #[deriving(Eq,IterBytes)]
896 pub enum MonoDataClass {
897 MonoBits, // Anything not treated differently from arbitrary integer data
898 MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
899 // FIXME(#3547)---scalars and floats are
900 // treated differently in most ABIs. But we
901 // should be doing something more detailed
906 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
907 match ty::get(t).sty {
908 ty::ty_float(_) => MonoFloat,
909 ty::ty_rptr(*) | ty::ty_uniq(*) |
910 ty::ty_box(*) | ty::ty_opaque_box(*) |
911 ty::ty_estr(ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_uniq) |
912 ty::ty_estr(ty::vstore_box) | ty::ty_evec(_, ty::vstore_box) |
913 ty::ty_bare_fn(*) => MonoNonNull,
914 // Is that everything? Would closures or slices qualify?
920 #[deriving(Eq,IterBytes)]
921 pub struct mono_id_ {
923 params: ~[mono_param_id]
926 pub type mono_id = @mono_id_;
928 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
929 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
930 return build::Select(cx, cond, b, a);
933 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
934 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
935 return build::Select(cx, cond, a, b);
938 pub fn align_to(cx: @mut Block, off: ValueRef, align: ValueRef) -> ValueRef {
939 let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
940 let bumped = build::Add(cx, off, mask);
941 return build::And(cx, bumped, build::Not(cx, mask));
944 pub fn path_str(sess: session::Session, p: &[path_elt]) -> ~str {
946 let mut first = true;
949 ast_map::path_name(s) | ast_map::path_mod(s) => {
955 r.push_str(sess.str_of(s));
962 pub fn monomorphize_type(bcx: @mut Block, t: ty::t) -> ty::t {
963 match bcx.fcx.param_substs {
965 ty::subst_tps(bcx.tcx(), substs.tys, substs.self_ty, t)
968 assert!(!ty::type_has_params(t));
969 assert!(!ty::type_has_self(t));
975 pub fn node_id_type(bcx: @mut Block, id: ast::NodeId) -> ty::t {
977 let t = ty::node_id_to_type(tcx, id);
978 monomorphize_type(bcx, t)
981 pub fn expr_ty(bcx: @mut Block, ex: &ast::expr) -> ty::t {
982 node_id_type(bcx, ex.id)
985 pub fn expr_ty_adjusted(bcx: @mut Block, ex: &ast::expr) -> ty::t {
987 let t = ty::expr_ty_adjusted(tcx, ex);
988 monomorphize_type(bcx, t)
991 pub fn node_id_type_params(bcx: @mut Block, id: ast::NodeId) -> ~[ty::t] {
993 let params = ty::node_id_to_type_params(tcx, id);
995 if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
997 fmt!("Type parameters for node %d include inference types: %s",
998 id, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
1001 match bcx.fcx.param_substs {
1003 do params.iter().transform |t| {
1004 ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1011 pub fn node_vtables(bcx: @mut Block, id: ast::NodeId)
1012 -> Option<typeck::vtable_res> {
1013 let raw_vtables = bcx.ccx().maps.vtable_map.find(&id);
1015 |&vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
1018 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
1019 -> typeck::vtable_res {
1020 resolve_vtables_under_param_substs(fcx.ccx.tcx,
1025 pub fn resolve_vtables_under_param_substs(tcx: ty::ctxt,
1026 param_substs: Option<@param_substs>,
1027 vts: typeck::vtable_res)
1028 -> typeck::vtable_res {
1029 @vts.iter().transform(|ds|
1030 resolve_param_vtables_under_param_substs(tcx,
1036 pub fn resolve_param_vtables_under_param_substs(
1038 param_substs: Option<@param_substs>,
1039 ds: typeck::vtable_param_res)
1040 -> typeck::vtable_param_res {
1041 @ds.iter().transform(
1042 |d| resolve_vtable_under_param_substs(tcx,
1050 // Apply the typaram substitutions in the FunctionContext to a vtable. This should
1051 // eliminate any vtable_params.
1052 pub fn resolve_vtable_in_fn_ctxt(fcx: &FunctionContext, vt: &typeck::vtable_origin)
1053 -> typeck::vtable_origin {
1054 resolve_vtable_under_param_substs(fcx.ccx.tcx,
1059 pub fn resolve_vtable_under_param_substs(tcx: ty::ctxt,
1060 param_substs: Option<@param_substs>,
1061 vt: &typeck::vtable_origin)
1062 -> typeck::vtable_origin {
1064 typeck::vtable_static(trait_id, ref tys, sub) => {
1065 let tys = match param_substs {
1067 do tys.iter().transform |t| {
1068 ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1073 typeck::vtable_static(
1075 resolve_vtables_under_param_substs(tcx, param_substs, sub))
1077 typeck::vtable_param(n_param, n_bound) => {
1078 match param_substs {
1080 find_vtable(tcx, substs, n_param, n_bound)
1084 "resolve_vtable_in_fn_ctxt: asked to lookup but \
1085 no vtables in the fn_ctxt!"))
1092 pub fn find_vtable(tcx: ty::ctxt,
1094 n_param: typeck::param_index,
1096 -> typeck::vtable_origin {
1097 debug!("find_vtable(n_param=%?, n_bound=%u, ps=%s)",
1098 n_param, n_bound, ps.repr(tcx));
1100 let param_bounds = match n_param {
1101 typeck::param_self => ps.self_vtables.expect("self vtables missing"),
1102 typeck::param_numbered(n) => {
1103 let tables = ps.vtables
1104 .expect("vtables missing where they are needed");
1108 param_bounds[n_bound].clone()
1111 pub fn dummy_substs(tps: ~[ty::t]) -> ty::substs {
1113 regions: ty::ErasedRegions,
1119 pub fn filename_and_line_num_from_span(bcx: @mut Block,
1120 span: span) -> (ValueRef, ValueRef) {
1121 let loc = bcx.sess().parse_sess.cm.lookup_char_pos(span.lo);
1122 let filename_cstr = C_cstr(bcx.ccx(), loc.file.name);
1123 let filename = build::PointerCast(bcx, filename_cstr, Type::i8p());
1124 let line = C_int(bcx.ccx(), loc.line as int);
1128 // Casts a Rust bool value to an i1.
1129 pub fn bool_to_i1(bcx: @mut Block, llval: ValueRef) -> ValueRef {
1130 build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(false))
1133 pub fn langcall(bcx: @mut Block, span: Option<span>, msg: &str,
1134 li: LangItem) -> ast::def_id {
1135 match bcx.tcx().lang_items.require(li) {
1138 let msg = fmt!("%s %s", msg, s);
1140 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
1141 None => { bcx.tcx().sess.fatal(msg); }