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::trans::debuginfo;
27 use middle::ty::substs;
30 use middle::borrowck::root_map_key;
31 use util::ppaux::{Repr};
33 use middle::trans::type_::Type;
35 use std::c_str::ToCStr;
36 use std::cast::transmute;
38 use std::hashmap::{HashMap};
39 use std::libc::{c_uint, c_longlong, c_ulonglong};
41 use syntax::ast::ident;
42 use syntax::ast_map::{path, path_elt};
43 use syntax::codemap::span;
44 use syntax::parse::token;
45 use syntax::{ast, ast_map};
47 pub use middle::trans::context::CrateContext;
49 pub fn gensym_name(name: &str) -> ident {
50 token::str_to_ident(fmt!("%s_%u", name, token::gensym(name)))
53 pub struct tydesc_info {
58 borrow_offset: ValueRef,
59 take_glue: Option<ValueRef>,
60 drop_glue: Option<ValueRef>,
61 free_glue: Option<ValueRef>,
62 visit_glue: Option<ValueRef>
66 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
68 * An "extern" is an LLVM symbol we wind up emitting an undefined external
69 * reference to. This means "we don't have the thing in this compilation unit,
70 * please make sure you link it in at runtime". This could be a reference to
71 * C code found in a C library, or rust code found in a rust crate.
73 * Most "externs" are implicitly declared (automatically) as a result of a
74 * user declaring an extern _module_ dependency; this causes the rust driver
75 * to locate an extern crate, scan its compilation metadata, and emit extern
76 * declarations for any symbols used by the declaring crate.
78 * A "foreign" is an extern that references C (or other non-rust ABI) code.
79 * There is no metadata to scan for extern references so in these cases either
80 * a header-digester like bindgen, or manual function prototypes, have to
81 * serve as declarators. So these are usually given explicitly as prototype
82 * declarations, in rust code, with ABI attributes on them noting which ABI to
85 * An "upcall" is a foreign call generated by the compiler (not corresponding
86 * to any user-written call in the code) into the runtime library, to perform
87 * some helper task such as bringing a task to life, allocating memory, etc.
92 n_static_tydescs: uint,
93 n_glues_created: uint,
101 llvm_insn_ctxt: ~[~str],
102 llvm_insns: HashMap<~str, uint>,
103 fn_stats: ~[(~str, uint, uint)] // (ident, time-in-ms, llvm-instructions)
106 pub struct BuilderRef_res {
110 impl Drop for BuilderRef_res {
113 llvm::LLVMDisposeBuilder(self.B);
118 pub fn BuilderRef_res(B: BuilderRef) -> BuilderRef_res {
124 pub type ExternMap = HashMap<@str, ValueRef>;
126 // Types used for llself.
127 pub struct ValSelfData {
133 // Here `self_ty` is the real type of the self parameter to this method. It
134 // will only be set in the case of default methods.
135 pub struct param_substs {
137 self_ty: Option<ty::t>,
138 vtables: Option<typeck::vtable_res>,
139 self_vtables: Option<typeck::vtable_param_res>
143 pub fn validate(&self) {
144 for t in self.tys.iter() { assert!(!ty::type_needs_infer(*t)); }
145 for t in self.self_ty.iter() { assert!(!ty::type_needs_infer(*t)); }
149 fn param_substs_to_str(this: ¶m_substs, tcx: ty::ctxt) -> ~str {
150 fmt!("param_substs {tys:%s, vtables:%s}",
152 this.vtables.repr(tcx))
155 impl Repr for param_substs {
156 fn repr(&self, tcx: ty::ctxt) -> ~str {
157 param_substs_to_str(self, tcx)
161 // Function context. Every LLVM function we create will have one of
163 pub struct FunctionContext {
164 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
165 // address of the first instruction in the sequence of
166 // instructions for this function that will go in the .text
167 // section of the executable we're generating.
170 // The implicit environment argument that arrives in the function we're
174 // The place to store the return value. If the return type is immediate,
175 // this is an alloca in the function. Otherwise, it's the hidden first
176 // parameter to the function. After function construction, this should
178 llretptr: Option<ValueRef>,
180 entry_bcx: Option<@mut Block>,
182 // These elements: "hoisted basic blocks" containing
183 // administrative activities that have to happen in only one place in
184 // the function, due to LLVM's quirks.
185 // A marker for the place where we want to insert the function's static
186 // allocas, so that LLVM will coalesce them into a single alloca call.
187 alloca_insert_pt: Option<ValueRef>,
188 llreturn: Option<BasicBlockRef>,
189 // The 'self' value currently in use in this function, if there
192 // NB: This is the type of the self *variable*, not the self *type*. The
193 // self type is set only for default methods, while the self variable is
194 // set for all methods.
195 llself: Option<ValSelfData>,
196 // The a value alloca'd for calls to upcalls.rust_personality. Used when
197 // outputting the resume instruction.
198 personality: Option<ValueRef>,
199 // If this is a for-loop body that returns, this holds the pointers needed
200 // for that (flagptr, retptr)
201 loop_ret: Option<(ValueRef, ValueRef)>,
203 // True if this function has an immediate return value, false otherwise.
204 // If this is false, the llretptr will alias the first argument of the
206 has_immediate_return_value: bool,
208 // Maps arguments to allocas created for them in llallocas.
209 llargs: @mut HashMap<ast::NodeId, ValueRef>,
210 // Maps the def_ids for local variables to the allocas created for
211 // them in llallocas.
212 lllocals: @mut HashMap<ast::NodeId, ValueRef>,
213 // Same as above, but for closure upvars
214 llupvars: @mut HashMap<ast::NodeId, ValueRef>,
216 // The NodeId of the function, or -1 if it doesn't correspond to
217 // a user-defined function.
220 // If this function is being monomorphized, this contains the type
221 // substitutions used.
222 param_substs: Option<@param_substs>,
224 // The source span and nesting context where this function comes from, for
225 // error reporting and symbol generation.
229 // This function's enclosing crate context.
230 ccx: @mut CrateContext,
232 // Used and maintained by the debuginfo module.
233 debug_context: Option<~debuginfo::FunctionDebugContext>
236 impl FunctionContext {
237 pub fn arg_pos(&self, arg: uint) -> uint {
238 if self.has_immediate_return_value {
245 pub fn out_arg_pos(&self) -> uint {
246 assert!(!self.has_immediate_return_value);
250 pub fn env_arg_pos(&self) -> uint {
251 if !self.has_immediate_return_value {
258 pub fn cleanup(&mut self) {
260 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt.unwrap());
262 // Remove the cycle between fcx and bcx, so memory can be freed
263 self.entry_bcx = None;
266 pub fn get_llreturn(&mut self) -> BasicBlockRef {
267 if self.llreturn.is_none() {
268 self.llreturn = Some(base::mk_return_basic_block(self.llfn));
271 self.llreturn.unwrap()
275 pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
276 if !ccx.do_not_commit_warning_issued {
277 ccx.do_not_commit_warning_issued = true;
278 ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
282 // Heap selectors. Indicate which heap something should go on.
288 heap_exchange_closure
291 #[deriving(Clone, Eq)]
294 normal_exit_and_unwind
298 clean(@fn(@mut Block) -> @mut Block, cleantype),
299 clean_temp(ValueRef, @fn(@mut Block) -> @mut Block, cleantype),
302 // Can't use deriving(Clone) because of the managed closure.
303 impl Clone for cleanup {
304 fn clone(&self) -> cleanup {
306 clean(f, ct) => clean(f, ct),
307 clean_temp(v, f, ct) => clean_temp(v, f, ct),
312 // Used to remember and reuse existing cleanup paths
313 // target: none means the path ends in an resume instruction
315 pub struct cleanup_path {
316 target: Option<BasicBlockRef>,
321 pub fn shrink_scope_clean(scope_info: &mut ScopeInfo, size: uint) {
322 scope_info.landing_pad = None;
323 scope_info.cleanup_paths = scope_info.cleanup_paths.iter()
324 .take_while(|&cu| cu.size <= size).map(|&x|x).collect();
327 pub fn grow_scope_clean(scope_info: &mut ScopeInfo) {
328 scope_info.landing_pad = None;
331 pub fn cleanup_type(cx: ty::ctxt, ty: ty::t) -> cleantype {
332 if ty::type_needs_unwind_cleanup(cx, ty) {
333 normal_exit_and_unwind
339 pub fn add_clean(bcx: @mut Block, val: ValueRef, t: ty::t) {
340 if !ty::type_needs_drop(bcx.tcx(), t) { return; }
342 debug!("add_clean(%s, %s, %s)", bcx.to_str(), bcx.val_to_str(val), t.repr(bcx.tcx()));
344 let cleanup_type = cleanup_type(bcx.tcx(), t);
345 do in_scope_cx(bcx, None) |scope_info| {
346 scope_info.cleanups.push(clean(|a| glue::drop_ty(a, val, t), cleanup_type));
347 grow_scope_clean(scope_info);
351 pub fn add_clean_temp_immediate(cx: @mut Block, val: ValueRef, ty: ty::t) {
352 if !ty::type_needs_drop(cx.tcx(), ty) { return; }
353 debug!("add_clean_temp_immediate(%s, %s, %s)",
354 cx.to_str(), cx.val_to_str(val),
356 let cleanup_type = cleanup_type(cx.tcx(), ty);
357 do in_scope_cx(cx, None) |scope_info| {
358 scope_info.cleanups.push(
359 clean_temp(val, |a| glue::drop_ty_immediate(a, val, ty),
361 grow_scope_clean(scope_info);
365 pub fn add_clean_temp_mem(bcx: @mut Block, val: ValueRef, t: ty::t) {
366 add_clean_temp_mem_in_scope_(bcx, None, val, t);
369 pub fn add_clean_temp_mem_in_scope(bcx: @mut Block,
370 scope_id: ast::NodeId,
373 add_clean_temp_mem_in_scope_(bcx, Some(scope_id), val, t);
376 pub fn add_clean_temp_mem_in_scope_(bcx: @mut Block, scope_id: Option<ast::NodeId>,
377 val: ValueRef, t: ty::t) {
378 if !ty::type_needs_drop(bcx.tcx(), t) { return; }
379 debug!("add_clean_temp_mem(%s, %s, %s)",
380 bcx.to_str(), bcx.val_to_str(val),
382 let cleanup_type = cleanup_type(bcx.tcx(), t);
383 do in_scope_cx(bcx, scope_id) |scope_info| {
384 scope_info.cleanups.push(clean_temp(val, |a| glue::drop_ty(a, val, t), cleanup_type));
385 grow_scope_clean(scope_info);
388 pub fn add_clean_return_to_mut(bcx: @mut Block,
389 scope_id: ast::NodeId,
390 root_key: root_map_key,
391 frozen_val_ref: ValueRef,
392 bits_val_ref: ValueRef,
393 filename_val: ValueRef,
394 line_val: ValueRef) {
395 //! When an `@mut` has been frozen, we have to
396 //! call the lang-item `return_to_mut` when the
397 //! freeze goes out of scope. We need to pass
398 //! in both the value which was frozen (`frozen_val`) and
399 //! the value (`bits_val_ref`) which was returned when the
400 //! box was frozen initially. Here, both `frozen_val_ref` and
401 //! `bits_val_ref` are in fact pointers to stack slots.
403 debug!("add_clean_return_to_mut(%s, %s, %s)",
405 bcx.val_to_str(frozen_val_ref),
406 bcx.val_to_str(bits_val_ref));
407 do in_scope_cx(bcx, Some(scope_id)) |scope_info| {
408 scope_info.cleanups.push(
411 |bcx| write_guard::return_to_mut(bcx, root_key, frozen_val_ref, bits_val_ref,
412 filename_val, line_val),
414 grow_scope_clean(scope_info);
417 pub fn add_clean_free(cx: @mut Block, ptr: ValueRef, heap: heap) {
418 let free_fn = match heap {
419 heap_managed | heap_managed_unique => {
420 let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_free(a, ptr);
423 heap_exchange | heap_exchange_closure => {
424 let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_exchange_free(a, ptr);
428 do in_scope_cx(cx, None) |scope_info| {
429 scope_info.cleanups.push(clean_temp(ptr, free_fn,
430 normal_exit_and_unwind));
431 grow_scope_clean(scope_info);
435 // Note that this only works for temporaries. We should, at some point, move
436 // to a system where we can also cancel the cleanup on local variables, but
437 // this will be more involved. For now, we simply zero out the local, and the
438 // drop glue checks whether it is zero.
439 pub fn revoke_clean(cx: @mut Block, val: ValueRef) {
440 do in_scope_cx(cx, None) |scope_info| {
441 let cleanup_pos = scope_info.cleanups.iter().position(
443 clean_temp(v, _, _) if v == val => true,
446 for i in cleanup_pos.iter() {
447 scope_info.cleanups =
448 vec::append(scope_info.cleanups.slice(0u, *i).to_owned(),
449 scope_info.cleanups.slice(*i + 1u,
450 scope_info.cleanups.len()));
451 shrink_scope_clean(scope_info, *i);
456 pub fn block_cleanups(bcx: @mut Block) -> ~[cleanup] {
459 Some(inf) => inf.cleanups.clone(),
463 pub struct ScopeInfo {
464 parent: Option<@mut ScopeInfo>,
465 loop_break: Option<@mut Block>,
466 loop_label: Option<ident>,
467 // A list of functions that must be run at when leaving this
468 // block, cleaning up any variables that were introduced in the
470 cleanups: ~[cleanup],
471 // Existing cleanup paths that may be reused, indexed by destination and
472 // cleared when the set of cleanups changes.
473 cleanup_paths: ~[cleanup_path],
474 // Unwinding landing pad. Also cleared when cleanups change.
475 landing_pad: Option<BasicBlockRef>,
476 // info about the AST node this scope originated from, if any
477 node_info: Option<NodeInfo>,
481 pub fn empty_cleanups(&mut self) -> bool {
482 self.cleanups.is_empty()
486 pub trait get_node_info {
487 fn info(&self) -> Option<NodeInfo>;
490 impl get_node_info for ast::expr {
491 fn info(&self) -> Option<NodeInfo> {
492 Some(NodeInfo {id: self.id,
493 callee_id: self.get_callee_id(),
498 impl get_node_info for ast::Block {
499 fn info(&self) -> Option<NodeInfo> {
500 Some(NodeInfo {id: self.id,
506 impl get_node_info for Option<@ast::expr> {
507 fn info(&self) -> Option<NodeInfo> {
508 self.chain_ref(|s| s.info())
512 pub struct NodeInfo {
514 callee_id: Option<ast::NodeId>,
518 // Basic block context. We create a block context for each basic block
519 // (single-entry, single-exit sequence of instructions) we generate from Rust
520 // code. Each basic block we generate is attached to a function, typically
521 // with many basic blocks per function. All the basic blocks attached to a
522 // function are organized as a directed graph.
524 // The BasicBlockRef returned from a call to
525 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
526 // block to the function pointed to by llfn. We insert
527 // instructions into that block by way of this block context.
528 // The block pointing to this one in the function's digraph.
532 parent: Option<@mut Block>,
533 // The current scope within this basic block
534 scope: Option<@mut ScopeInfo>,
535 // Is this block part of a landing pad?
537 // info about the AST node this block originated from, if any
538 node_info: Option<NodeInfo>,
539 // The function context for the function to which this block is
541 fcx: @mut FunctionContext
546 pub fn new(llbb: BasicBlockRef,
547 parent: Option<@mut Block>,
549 node_info: Option<NodeInfo>,
550 fcx: @mut FunctionContext)
559 node_info: node_info,
564 pub fn ccx(&self) -> @mut CrateContext { self.fcx.ccx }
565 pub fn tcx(&self) -> ty::ctxt { self.fcx.ccx.tcx }
566 pub fn sess(&self) -> Session { self.fcx.ccx.sess }
568 pub fn ident(&self, ident: ident) -> @str {
569 token::ident_to_str(&ident)
572 pub fn node_id_to_str(&self, id: ast::NodeId) -> ~str {
573 ast_map::node_id_to_str(self.tcx().items, id, self.sess().intr())
576 pub fn expr_to_str(&self, e: @ast::expr) -> ~str {
580 pub fn expr_is_lval(&self, e: &ast::expr) -> bool {
581 ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
584 pub fn expr_kind(&self, e: &ast::expr) -> ty::ExprKind {
585 ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
588 pub fn def(&self, nid: ast::NodeId) -> ast::def {
589 match self.tcx().def_map.find(&nid) {
592 self.tcx().sess.bug(fmt!(
593 "No def associated with node id %?", nid));
598 pub fn val_to_str(&self, val: ValueRef) -> ~str {
599 self.ccx().tn.val_to_str(val)
602 pub fn llty_str(&self, ty: Type) -> ~str {
603 self.ccx().tn.type_to_str(ty)
606 pub fn ty_to_str(&self, t: ty::t) -> ~str {
610 pub fn to_str(&self) -> ~str {
612 match self.node_info {
613 Some(node_info) => fmt!("[block %d]", node_info.id),
614 None => fmt!("[block %x]", transmute(&*self)),
625 pub fn rslt(bcx: @mut Block, val: ValueRef) -> Result {
626 Result {bcx: bcx, val: val}
630 pub fn unpack(&self, bcx: &mut @mut Block) -> ValueRef {
636 pub fn val_ty(v: ValueRef) -> Type {
638 Type::from_ref(llvm::LLVMTypeOf(v))
642 pub fn in_scope_cx(cx: @mut Block, scope_id: Option<ast::NodeId>, f: &fn(si: &mut ScopeInfo)) {
644 let mut cur_scope = cur.scope;
646 cur_scope = match cur_scope {
647 Some(inf) => match scope_id {
648 Some(wanted) => match inf.node_info {
649 Some(NodeInfo { id: actual, _ }) if wanted == actual => {
650 debug!("in_scope_cx: selected cur=%s (cx=%s)",
651 cur.to_str(), cx.to_str());
658 debug!("in_scope_cx: selected cur=%s (cx=%s)",
659 cur.to_str(), cx.to_str());
665 cur = block_parent(cur);
672 pub fn block_parent(cx: @mut Block) -> @mut Block {
675 None => cx.sess().bug(fmt!("block_parent called on root block %?",
681 // Let T be the content of a box @T. tuplify_box_ty(t) returns the
682 // representation of @T as a tuple (i.e., the ty::t version of what T_box()
684 pub fn tuplify_box_ty(tcx: ty::ctxt, t: ty::t) -> ty::t {
685 let ptr = ty::mk_ptr(
687 ty::mt {ty: ty::mk_i8(), mutbl: ast::m_imm}
689 return ty::mk_tup(tcx, ~[ty::mk_uint(), ty::mk_type(tcx),
694 // LLVM constant constructors.
695 pub fn C_null(t: Type) -> ValueRef {
697 llvm::LLVMConstNull(t.to_ref())
701 pub fn C_undef(t: Type) -> ValueRef {
703 llvm::LLVMGetUndef(t.to_ref())
707 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
709 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
713 pub fn C_floating(s: &str, t: Type) -> ValueRef {
715 do s.to_c_str().with_ref |buf| {
716 llvm::LLVMConstRealOfString(t.to_ref(), buf)
721 pub fn C_nil() -> ValueRef {
725 pub fn C_bool(val: bool) -> ValueRef {
726 C_integral(Type::bool(), val as u64, false)
729 pub fn C_i1(val: bool) -> ValueRef {
730 C_integral(Type::i1(), val as u64, false)
733 pub fn C_i32(i: i32) -> ValueRef {
734 return C_integral(Type::i32(), i as u64, true);
737 pub fn C_i64(i: i64) -> ValueRef {
738 return C_integral(Type::i64(), i as u64, true);
741 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
742 return C_integral(cx.int_type, i as u64, true);
745 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
746 return C_integral(cx.int_type, i as u64, false);
749 pub fn C_u8(i: uint) -> ValueRef {
750 return C_integral(Type::i8(), i as u64, false);
754 // This is a 'c-like' raw string, which differs from
755 // our boxed-and-length-annotated strings.
756 pub fn C_cstr(cx: &mut CrateContext, s: @str) -> ValueRef {
758 match cx.const_cstr_cache.find_equiv(&s) {
759 Some(&llval) => return llval,
763 let sc = do s.to_c_str().with_ref |buf| {
764 llvm::LLVMConstStringInContext(cx.llcx, buf, s.len() as c_uint, False)
767 let gsym = token::gensym("str");
768 let g = do fmt!("str%u", gsym).to_c_str().with_ref |buf| {
769 llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
771 llvm::LLVMSetInitializer(g, sc);
772 llvm::LLVMSetGlobalConstant(g, True);
773 lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
775 cx.const_cstr_cache.insert(s, g);
781 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
782 // you will be kicked off fast isel. See issue #4352 for an example of this.
783 pub fn C_estr_slice(cx: &mut CrateContext, s: @str) -> ValueRef {
786 let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p().to_ref());
787 C_struct([cs, C_uint(cx, len)])
791 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
794 let mut elts: ~[ValueRef] = ~[];
795 while i < size { elts.push(C_u8(0u)); i += 1u; }
796 return llvm::LLVMConstArray(Type::i8().to_ref(),
797 vec::raw::to_ptr(elts), elts.len() as c_uint);
801 pub fn C_struct(elts: &[ValueRef]) -> ValueRef {
803 do elts.as_imm_buf |ptr, len| {
804 llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, False)
809 pub fn C_packed_struct(elts: &[ValueRef]) -> ValueRef {
811 do elts.as_imm_buf |ptr, len| {
812 llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, True)
817 pub fn C_named_struct(T: Type, elts: &[ValueRef]) -> ValueRef {
819 do elts.as_imm_buf |ptr, len| {
820 llvm::LLVMConstNamedStruct(T.to_ref(), ptr, len as c_uint)
825 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
827 return llvm::LLVMConstArray(ty.to_ref(), vec::raw::to_ptr(elts), elts.len() as c_uint);
831 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
833 let ptr = cast::transmute(vec::raw::to_ptr(bytes));
834 return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
838 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
840 llvm::LLVMGetParam(fndecl, param as c_uint)
844 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
847 let r = do us.as_imm_buf |p, len| {
848 llvm::LLVMConstExtractValue(v, p, len as c_uint)
851 debug!("const_get_elt(v=%s, us=%?, r=%s)",
852 cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
858 pub fn is_const(v: ValueRef) -> bool {
860 llvm::LLVMIsConstant(v) == True
864 pub fn const_to_int(v: ValueRef) -> c_longlong {
866 llvm::LLVMConstIntGetSExtValue(v)
870 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
872 llvm::LLVMConstIntGetZExtValue(v)
876 pub fn is_undef(val: ValueRef) -> bool {
878 llvm::LLVMIsUndef(val) != False
882 pub fn is_null(val: ValueRef) -> bool {
884 llvm::LLVMIsNull(val) != False
888 // Used to identify cached monomorphized functions and vtables
889 #[deriving(Eq,IterBytes)]
890 pub enum mono_param_id {
891 mono_precise(ty::t, Option<@~[mono_id]>),
893 mono_repr(uint /* size */,
899 #[deriving(Eq,IterBytes)]
900 pub enum MonoDataClass {
901 MonoBits, // Anything not treated differently from arbitrary integer data
902 MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
903 // FIXME(#3547)---scalars and floats are
904 // treated differently in most ABIs. But we
905 // should be doing something more detailed
910 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
911 match ty::get(t).sty {
912 ty::ty_float(_) => MonoFloat,
913 ty::ty_rptr(*) | ty::ty_uniq(*) |
914 ty::ty_box(*) | ty::ty_opaque_box(*) |
915 ty::ty_estr(ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_uniq) |
916 ty::ty_estr(ty::vstore_box) | ty::ty_evec(_, ty::vstore_box) |
917 ty::ty_bare_fn(*) => MonoNonNull,
918 // Is that everything? Would closures or slices qualify?
924 #[deriving(Eq,IterBytes)]
925 pub struct mono_id_ {
927 params: ~[mono_param_id]
930 pub type mono_id = @mono_id_;
932 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
933 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
934 return build::Select(cx, cond, b, a);
937 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
938 let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
939 return build::Select(cx, cond, a, b);
942 pub fn align_to(cx: @mut Block, off: ValueRef, align: ValueRef) -> ValueRef {
943 let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
944 let bumped = build::Add(cx, off, mask);
945 return build::And(cx, bumped, build::Not(cx, mask));
948 pub fn path_str(sess: session::Session, p: &[path_elt]) -> ~str {
950 let mut first = true;
953 ast_map::path_name(s) | ast_map::path_mod(s) => {
959 r.push_str(sess.str_of(s));
966 pub fn monomorphize_type(bcx: @mut Block, t: ty::t) -> ty::t {
967 match bcx.fcx.param_substs {
969 ty::subst_tps(bcx.tcx(), substs.tys, substs.self_ty, t)
972 assert!(!ty::type_has_params(t));
973 assert!(!ty::type_has_self(t));
979 pub fn node_id_type(bcx: @mut Block, id: ast::NodeId) -> ty::t {
981 let t = ty::node_id_to_type(tcx, id);
982 monomorphize_type(bcx, t)
985 pub fn expr_ty(bcx: @mut Block, ex: &ast::expr) -> ty::t {
986 node_id_type(bcx, ex.id)
989 pub fn expr_ty_adjusted(bcx: @mut Block, ex: &ast::expr) -> ty::t {
991 let t = ty::expr_ty_adjusted(tcx, ex);
992 monomorphize_type(bcx, t)
995 pub fn node_id_type_params(bcx: @mut Block, id: ast::NodeId) -> ~[ty::t] {
997 let params = ty::node_id_to_type_params(tcx, id);
999 if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
1001 fmt!("Type parameters for node %d include inference types: %s",
1002 id, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
1005 match bcx.fcx.param_substs {
1007 do params.iter().map |t| {
1008 ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1015 pub fn node_vtables(bcx: @mut Block, id: ast::NodeId)
1016 -> Option<typeck::vtable_res> {
1017 let raw_vtables = bcx.ccx().maps.vtable_map.find(&id);
1018 raw_vtables.map_move(|vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
1021 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
1022 -> typeck::vtable_res {
1023 resolve_vtables_under_param_substs(fcx.ccx.tcx,
1028 pub fn resolve_vtables_under_param_substs(tcx: ty::ctxt,
1029 param_substs: Option<@param_substs>,
1030 vts: typeck::vtable_res)
1031 -> typeck::vtable_res {
1032 @vts.iter().map(|ds|
1033 resolve_param_vtables_under_param_substs(tcx,
1039 pub fn resolve_param_vtables_under_param_substs(
1041 param_substs: Option<@param_substs>,
1042 ds: typeck::vtable_param_res)
1043 -> typeck::vtable_param_res {
1045 |d| resolve_vtable_under_param_substs(tcx,
1053 // Apply the typaram substitutions in the FunctionContext to a vtable. This should
1054 // eliminate any vtable_params.
1055 pub fn resolve_vtable_in_fn_ctxt(fcx: &FunctionContext, vt: &typeck::vtable_origin)
1056 -> typeck::vtable_origin {
1057 resolve_vtable_under_param_substs(fcx.ccx.tcx,
1062 pub fn resolve_vtable_under_param_substs(tcx: ty::ctxt,
1063 param_substs: Option<@param_substs>,
1064 vt: &typeck::vtable_origin)
1065 -> typeck::vtable_origin {
1067 typeck::vtable_static(trait_id, ref tys, sub) => {
1068 let tys = match param_substs {
1070 do tys.iter().map |t| {
1071 ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1076 typeck::vtable_static(
1078 resolve_vtables_under_param_substs(tcx, param_substs, sub))
1080 typeck::vtable_param(n_param, n_bound) => {
1081 match param_substs {
1083 find_vtable(tcx, substs, n_param, n_bound)
1087 "resolve_vtable_in_fn_ctxt: asked to lookup but \
1088 no vtables in the fn_ctxt!"))
1095 pub fn find_vtable(tcx: ty::ctxt,
1097 n_param: typeck::param_index,
1099 -> typeck::vtable_origin {
1100 debug!("find_vtable(n_param=%?, n_bound=%u, ps=%s)",
1101 n_param, n_bound, ps.repr(tcx));
1103 let param_bounds = match n_param {
1104 typeck::param_self => ps.self_vtables.expect("self vtables missing"),
1105 typeck::param_numbered(n) => {
1106 let tables = ps.vtables
1107 .expect("vtables missing where they are needed");
1111 param_bounds[n_bound].clone()
1114 pub fn dummy_substs(tps: ~[ty::t]) -> ty::substs {
1116 regions: ty::ErasedRegions,
1122 pub fn filename_and_line_num_from_span(bcx: @mut Block,
1123 span: span) -> (ValueRef, ValueRef) {
1124 let loc = bcx.sess().parse_sess.cm.lookup_char_pos(span.lo);
1125 let filename_cstr = C_cstr(bcx.ccx(), loc.file.name);
1126 let filename = build::PointerCast(bcx, filename_cstr, Type::i8p());
1127 let line = C_int(bcx.ccx(), loc.line as int);
1131 // Casts a Rust bool value to an i1.
1132 pub fn bool_to_i1(bcx: @mut Block, llval: ValueRef) -> ValueRef {
1133 build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(false))
1136 pub fn langcall(bcx: @mut Block, span: Option<span>, msg: &str,
1137 li: LangItem) -> ast::def_id {
1138 match bcx.tcx().lang_items.require(li) {
1141 let msg = fmt!("%s %s", msg, s);
1143 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
1144 None => { bcx.tcx().sess.fatal(msg); }