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.
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 #![allow(non_camel_case_types, non_snake_case)]
13 //! Code that is useful in various trans modules.
15 pub use self::ExprOrMethodCall::*;
19 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ContextRef};
20 use llvm::{True, False, Bool};
24 use middle::lang_items::LangItem;
25 use middle::mem_categorization as mc;
27 use middle::subst::{self, Subst, Substs};
35 use trans::monomorphize;
36 use trans::type_::Type;
39 use middle::ty::{self, HasProjectionTypes, Ty};
41 use middle::ty_fold::{TypeFolder, TypeFoldable};
42 use util::ppaux::Repr;
43 use util::nodemap::{FnvHashMap, NodeMap};
45 use arena::TypedArena;
46 use libc::{c_uint, c_char};
47 use std::ffi::CString;
48 use std::cell::{Cell, RefCell};
50 use syntax::ast::Ident;
52 use syntax::ast_map::{PathElem, PathName};
53 use syntax::codemap::Span;
54 use syntax::parse::token::InternedString;
55 use syntax::parse::token;
56 use util::common::memoized;
57 use util::nodemap::FnvHashSet;
59 pub use trans::context::CrateContext;
61 // Is the type's representation size known at compile time?
62 pub fn type_is_sized<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
63 ty::type_contents(cx, ty).is_sized(cx)
66 pub fn lltype_is_sized<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
68 ty::ty_open(_) => true,
69 _ => type_is_sized(cx, ty),
73 pub fn type_is_fat_ptr<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
75 ty::ty_ptr(ty::mt{ty, ..}) |
76 ty::ty_rptr(_, ty::mt{ty, ..}) |
78 !type_is_sized(cx, ty)
86 // Return the smallest part of `ty` which is unsized. Fails if `ty` is sized.
87 // 'Smallest' here means component of the static representation of the type; not
88 // the size of an object at runtime.
89 pub fn unsized_part_of_type<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
91 ty::ty_str | ty::ty_trait(..) | ty::ty_vec(..) => ty,
92 ty::ty_struct(def_id, substs) => {
93 let unsized_fields: Vec<_> =
94 ty::struct_fields(cx, def_id, substs)
97 .filter(|ty| !type_is_sized(cx, *ty))
100 // Exactly one of the fields must be unsized.
101 assert!(unsized_fields.len() == 1);
103 unsized_part_of_type(cx, unsized_fields[0])
106 assert!(type_is_sized(cx, ty),
107 "unsized_part_of_type failed even though ty is unsized");
108 panic!("called unsized_part_of_type with sized ty");
113 // Some things don't need cleanups during unwinding because the
114 // task can free them all at once later. Currently only things
115 // that only contain scalars and shared boxes can avoid unwind
117 pub fn type_needs_unwind_cleanup<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
118 return memoized(ccx.needs_unwind_cleanup_cache(), ty, |ty| {
119 type_needs_unwind_cleanup_(ccx.tcx(), ty, &mut FnvHashSet::new())
122 fn type_needs_unwind_cleanup_<'tcx>(tcx: &ty::ctxt<'tcx>,
124 tycache: &mut FnvHashSet<Ty<'tcx>>)
127 // Prevent infinite recursion
128 if !tycache.insert(ty) {
132 let mut needs_unwind_cleanup = false;
133 ty::maybe_walk_ty(ty, |ty| {
134 needs_unwind_cleanup |= match ty.sty {
135 ty::ty_bool | ty::ty_int(_) | ty::ty_uint(_) |
136 ty::ty_float(_) | ty::ty_tup(_) | ty::ty_ptr(_) => false,
138 ty::ty_enum(did, substs) =>
139 ty::enum_variants(tcx, did).iter().any(|v|
140 v.args.iter().any(|&aty| {
141 let t = aty.subst(tcx, substs);
142 type_needs_unwind_cleanup_(tcx, t, tycache)
148 !needs_unwind_cleanup
154 pub fn type_needs_drop<'tcx>(cx: &ty::ctxt<'tcx>,
157 ty::type_contents(cx, ty).needs_drop(cx)
160 fn type_is_newtype_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
161 ty: Ty<'tcx>) -> bool {
163 ty::ty_struct(def_id, substs) => {
164 let fields = ty::struct_fields(ccx.tcx(), def_id, substs);
167 token::special_idents::unnamed_field.name &&
168 type_is_immediate(ccx, fields[0].mt.ty)
174 pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
175 use trans::machine::llsize_of_alloc;
176 use trans::type_of::sizing_type_of;
179 let simple = ty::type_is_scalar(ty) ||
180 ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
181 type_is_newtype_immediate(ccx, ty) ||
182 ty::type_is_simd(tcx, ty);
183 if simple && !type_is_fat_ptr(tcx, ty) {
186 if !type_is_sized(tcx, ty) {
190 ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) |
191 ty::ty_unboxed_closure(..) => {
192 let llty = sizing_type_of(ccx, ty);
193 llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type())
195 _ => type_is_zero_size(ccx, ty)
199 /// Identify types which have size zero at runtime.
200 pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
201 use trans::machine::llsize_of_alloc;
202 use trans::type_of::sizing_type_of;
203 let llty = sizing_type_of(ccx, ty);
204 llsize_of_alloc(ccx, llty) == 0
207 /// Identifies types which we declare to be equivalent to `void` in C for the purpose of function
208 /// return types. These are `()`, bot, and uninhabited enums. Note that all such types are also
209 /// zero-size, but not all zero-size types use a `void` return type (in order to aid with C ABI
211 pub fn return_type_is_void(ccx: &CrateContext, ty: Ty) -> bool {
212 ty::type_is_nil(ty) || ty::type_is_empty(ccx.tcx(), ty)
215 /// Generates a unique symbol based off the name given. This is used to create
216 /// unique symbols for things like closures.
217 pub fn gensym_name(name: &str) -> PathElem {
218 let num = token::gensym(name).uint();
219 // use one colon which will get translated to a period by the mangler, and
220 // we're guaranteed that `num` is globally unique for this crate.
221 PathName(token::gensym(format!("{}:{}", name, num)[]))
225 pub struct tydesc_info<'tcx> {
227 pub tydesc: ValueRef,
234 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
236 * An "extern" is an LLVM symbol we wind up emitting an undefined external
237 * reference to. This means "we don't have the thing in this compilation unit,
238 * please make sure you link it in at runtime". This could be a reference to
239 * C code found in a C library, or rust code found in a rust crate.
241 * Most "externs" are implicitly declared (automatically) as a result of a
242 * user declaring an extern _module_ dependency; this causes the rust driver
243 * to locate an extern crate, scan its compilation metadata, and emit extern
244 * declarations for any symbols used by the declaring crate.
246 * A "foreign" is an extern that references C (or other non-rust ABI) code.
247 * There is no metadata to scan for extern references so in these cases either
248 * a header-digester like bindgen, or manual function prototypes, have to
249 * serve as declarators. So these are usually given explicitly as prototype
250 * declarations, in rust code, with ABI attributes on them noting which ABI to
253 * An "upcall" is a foreign call generated by the compiler (not corresponding
254 * to any user-written call in the code) into the runtime library, to perform
255 * some helper task such as bringing a task to life, allocating memory, etc.
260 pub struct NodeInfo {
265 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
266 NodeInfo { id: expr.id, span: expr.span }
269 pub struct BuilderRef_res {
273 impl Drop for BuilderRef_res {
276 llvm::LLVMDisposeBuilder(self.b);
281 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
287 pub type ExternMap = FnvHashMap<String, ValueRef>;
289 pub fn validate_substs(substs: &Substs) {
290 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
293 // work around bizarre resolve errors
294 type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
295 type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
297 // Function context. Every LLVM function we create will have one of
299 pub struct FunctionContext<'a, 'tcx: 'a> {
300 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
301 // address of the first instruction in the sequence of
302 // instructions for this function that will go in the .text
303 // section of the executable we're generating.
306 // always an empty parameter-environment
307 pub param_env: ty::ParameterEnvironment<'a, 'tcx>,
309 // The environment argument in a closure.
310 pub llenv: Option<ValueRef>,
312 // A pointer to where to store the return value. If the return type is
313 // immediate, this points to an alloca in the function. Otherwise, it's a
314 // pointer to the hidden first parameter of the function. After function
315 // construction, this should always be Some.
316 pub llretslotptr: Cell<Option<ValueRef>>,
318 // These pub elements: "hoisted basic blocks" containing
319 // administrative activities that have to happen in only one place in
320 // the function, due to LLVM's quirks.
321 // A marker for the place where we want to insert the function's static
322 // allocas, so that LLVM will coalesce them into a single alloca call.
323 pub alloca_insert_pt: Cell<Option<ValueRef>>,
324 pub llreturn: Cell<Option<BasicBlockRef>>,
326 // If the function has any nested return's, including something like:
327 // fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then
328 // we use a separate alloca for each return
329 pub needs_ret_allocas: bool,
331 // The a value alloca'd for calls to upcalls.rust_personality. Used when
332 // outputting the resume instruction.
333 pub personality: Cell<Option<ValueRef>>,
335 // True if the caller expects this fn to use the out pointer to
336 // return. Either way, your code should write into the slot llretslotptr
337 // points to, but if this value is false, that slot will be a local alloca.
338 pub caller_expects_out_pointer: bool,
340 // Maps the DefId's for local variables to the allocas created for
341 // them in llallocas.
342 pub lllocals: RefCell<NodeMap<LvalueDatum<'tcx>>>,
344 // Same as above, but for closure upvars
345 pub llupvars: RefCell<NodeMap<ValueRef>>,
347 // The NodeId of the function, or -1 if it doesn't correspond to
348 // a user-defined function.
351 // If this function is being monomorphized, this contains the type
352 // substitutions used.
353 pub param_substs: &'a Substs<'tcx>,
355 // The source span and nesting context where this function comes from, for
356 // error reporting and symbol generation.
357 pub span: Option<Span>,
359 // The arena that blocks are allocated from.
360 pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>,
362 // This function's enclosing crate context.
363 pub ccx: &'a CrateContext<'a, 'tcx>,
365 // Used and maintained by the debuginfo module.
366 pub debug_context: debuginfo::FunctionDebugContext,
369 pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>,
371 pub cfg: Option<cfg::CFG>,
374 impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
375 pub fn arg_pos(&self, arg: uint) -> uint {
376 let arg = self.env_arg_pos() + arg;
377 if self.llenv.is_some() {
384 pub fn env_arg_pos(&self) -> uint {
385 if self.caller_expects_out_pointer {
392 pub fn cleanup(&self) {
394 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
400 pub fn get_llreturn(&self) -> BasicBlockRef {
401 if self.llreturn.get().is_none() {
403 self.llreturn.set(Some(unsafe {
404 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn,
405 "return\0".as_ptr() as *const _)
409 self.llreturn.get().unwrap()
412 pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>,
413 output: ty::FnOutput<'tcx>,
414 name: &str) -> ValueRef {
415 if self.needs_ret_allocas {
416 base::alloca_no_lifetime(bcx, match output {
417 ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type),
418 ty::FnDiverging => Type::void(bcx.ccx())
421 self.llretslotptr.get().unwrap()
425 pub fn new_block(&'a self,
428 opt_node_id: Option<ast::NodeId>)
431 let name = CString::from_slice(name.as_bytes());
432 let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
435 BlockS::new(llbb, is_lpad, opt_node_id, self)
439 pub fn new_id_block(&'a self,
441 node_id: ast::NodeId)
443 self.new_block(false, name, Some(node_id))
446 pub fn new_temp_block(&'a self,
449 self.new_block(false, name, None)
452 pub fn join_blocks(&'a self,
454 in_cxs: &[Block<'a, 'tcx>])
456 let out = self.new_id_block("join", id);
457 let mut reachable = false;
458 for bcx in in_cxs.iter() {
459 if !bcx.unreachable.get() {
460 build::Br(*bcx, out.llbb);
465 build::Unreachable(out);
470 pub fn monomorphize<T>(&self, value: &T) -> T
471 where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
473 monomorphize::apply_param_substs(self.ccx.tcx(),
479 // Basic block context. We create a block context for each basic block
480 // (single-entry, single-exit sequence of instructions) we generate from Rust
481 // code. Each basic block we generate is attached to a function, typically
482 // with many basic blocks per function. All the basic blocks attached to a
483 // function are organized as a directed graph.
484 pub struct BlockS<'blk, 'tcx: 'blk> {
485 // The BasicBlockRef returned from a call to
486 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
487 // block to the function pointed to by llfn. We insert
488 // instructions into that block by way of this block context.
489 // The block pointing to this one in the function's digraph.
490 pub llbb: BasicBlockRef,
491 pub terminated: Cell<bool>,
492 pub unreachable: Cell<bool>,
494 // Is this block part of a landing pad?
497 // AST node-id associated with this block, if any. Used for
498 // debugging purposes only.
499 pub opt_node_id: Option<ast::NodeId>,
501 // The function context for the function to which this block is
503 pub fcx: &'blk FunctionContext<'blk, 'tcx>,
506 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
508 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
509 pub fn new(llbb: BasicBlockRef,
511 opt_node_id: Option<ast::NodeId>,
512 fcx: &'blk FunctionContext<'blk, 'tcx>)
513 -> Block<'blk, 'tcx> {
514 fcx.block_arena.alloc(BlockS {
516 terminated: Cell::new(false),
517 unreachable: Cell::new(false),
519 opt_node_id: opt_node_id,
524 pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
527 pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
530 pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
532 pub fn ident(&self, ident: Ident) -> String {
533 token::get_ident(ident).get().to_string()
536 pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
537 self.tcx().map.node_to_string(id).to_string()
540 pub fn expr_to_string(&self, e: &ast::Expr) -> String {
544 pub fn def(&self, nid: ast::NodeId) -> def::Def {
545 match self.tcx().def_map.borrow().get(&nid) {
546 Some(v) => v.clone(),
548 self.tcx().sess.bug(format!(
549 "no def associated with node id {}", nid)[]);
554 pub fn val_to_string(&self, val: ValueRef) -> String {
555 self.ccx().tn().val_to_string(val)
558 pub fn llty_str(&self, ty: Type) -> String {
559 self.ccx().tn().type_to_string(ty)
562 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
566 pub fn to_str(&self) -> String {
567 format!("[block {:p}]", self)
570 pub fn monomorphize<T>(&self, value: &T) -> T
571 where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
573 monomorphize::apply_param_substs(self.tcx(),
574 self.fcx.param_substs,
579 impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> {
580 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
584 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
585 Ok(node_id_type(self, id))
588 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> {
589 Ok(expr_ty_adjusted(self, expr))
592 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
597 .map(|method| monomorphize_type(self, method.ty))
600 fn node_method_origin(&self, method_call: ty::MethodCall)
601 -> Option<ty::MethodOrigin<'tcx>>
607 .map(|method| method.origin.clone())
610 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
611 &self.tcx().adjustments
614 fn is_method_call(&self, id: ast::NodeId) -> bool {
615 self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id))
618 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
619 self.tcx().region_maps.temporary_scope(rvalue_id)
622 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow> {
623 Some(self.tcx().upvar_borrow_map.borrow()[upvar_id].clone())
626 fn capture_mode(&self, closure_expr_id: ast::NodeId)
627 -> ast::CaptureClause {
628 self.tcx().capture_modes.borrow()[closure_expr_id].clone()
631 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
632 self.fcx.param_env.type_moves_by_default(span, ty)
636 impl<'blk, 'tcx> ty::UnboxedClosureTyper<'tcx> for BlockS<'blk, 'tcx> {
637 fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx> {
641 fn unboxed_closure_kind(&self,
643 -> ty::UnboxedClosureKind
645 let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
646 typer.unboxed_closure_kind(def_id)
649 fn unboxed_closure_type(&self,
651 substs: &subst::Substs<'tcx>)
652 -> ty::ClosureTy<'tcx>
654 let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
655 typer.unboxed_closure_type(def_id, substs)
658 fn unboxed_closure_upvars(&self,
660 substs: &Substs<'tcx>)
661 -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>>
663 let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
664 typer.unboxed_closure_upvars(def_id, substs)
668 pub struct Result<'blk, 'tcx: 'blk> {
669 pub bcx: Block<'blk, 'tcx>,
673 impl<'b, 'tcx> Result<'b, 'tcx> {
674 pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
682 pub fn val_ty(v: ValueRef) -> Type {
684 Type::from_ref(llvm::LLVMTypeOf(v))
688 // LLVM constant constructors.
689 pub fn C_null(t: Type) -> ValueRef {
691 llvm::LLVMConstNull(t.to_ref())
695 pub fn C_undef(t: Type) -> ValueRef {
697 llvm::LLVMGetUndef(t.to_ref())
701 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
703 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
707 pub fn C_floating(s: &str, t: Type) -> ValueRef {
709 let s = CString::from_slice(s.as_bytes());
710 llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr())
714 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
715 C_struct(ccx, &[], false)
718 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
719 C_integral(Type::i1(ccx), val as u64, false)
722 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
723 C_integral(Type::i32(ccx), i as u64, true)
726 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
727 C_integral(Type::i64(ccx), i as u64, true)
730 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
731 C_integral(Type::i64(ccx), i, false)
734 pub fn C_int<I: AsI64>(ccx: &CrateContext, i: I) -> ValueRef {
737 match machine::llbitsize_of_real(ccx, ccx.int_type()) {
738 32 => assert!(v < (1<<31) && v >= -(1<<31)),
740 n => panic!("unsupported target size: {}", n)
743 C_integral(ccx.int_type(), v as u64, true)
746 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
749 match machine::llbitsize_of_real(ccx, ccx.int_type()) {
750 32 => assert!(v < (1<<32)),
752 n => panic!("unsupported target size: {}", n)
755 C_integral(ccx.int_type(), v, false)
758 pub trait AsI64 { fn as_i64(self) -> i64; }
759 pub trait AsU64 { fn as_u64(self) -> u64; }
761 // FIXME: remove the intptr conversions, because they
762 // are host-architecture-dependent
763 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
764 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
765 impl AsI64 for int { fn as_i64(self) -> i64 { self as i64 }}
767 impl AsU64 for u64 { fn as_u64(self) -> u64 { self as u64 }}
768 impl AsU64 for u32 { fn as_u64(self) -> u64 { self as u64 }}
769 impl AsU64 for uint { fn as_u64(self) -> u64 { self as u64 }}
771 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
772 C_integral(Type::i8(ccx), i as u64, false)
776 // This is a 'c-like' raw string, which differs from
777 // our boxed-and-length-annotated strings.
778 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
780 match cx.const_cstr_cache().borrow().get(&s) {
781 Some(&llval) => return llval,
785 let sc = llvm::LLVMConstStringInContext(cx.llcx(),
786 s.get().as_ptr() as *const c_char,
787 s.get().len() as c_uint,
788 !null_terminated as Bool);
790 let gsym = token::gensym("str");
791 let buf = CString::from_vec(format!("str{}", gsym.uint()).into_bytes());
792 let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf.as_ptr());
793 llvm::LLVMSetInitializer(g, sc);
794 llvm::LLVMSetGlobalConstant(g, True);
795 llvm::SetLinkage(g, llvm::InternalLinkage);
797 cx.const_cstr_cache().borrow_mut().insert(s, g);
802 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
803 // you will be kicked off fast isel. See issue #4352 for an example of this.
804 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
805 let len = s.get().len();
806 let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
807 C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
810 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
812 let len = data.len();
813 let lldata = C_bytes(cx, data);
815 let gsym = token::gensym("binary");
816 let name = format!("binary{}", gsym.uint());
817 let name = CString::from_vec(name.into_bytes());
818 let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(),
820 llvm::LLVMSetInitializer(g, lldata);
821 llvm::LLVMSetGlobalConstant(g, True);
822 llvm::SetLinkage(g, llvm::InternalLinkage);
824 let cs = consts::ptrcast(g, Type::i8p(cx));
825 C_struct(cx, &[cs, C_uint(cx, len)], false)
829 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
830 C_struct_in_context(cx.llcx(), elts, packed)
833 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
835 llvm::LLVMConstStructInContext(llcx,
836 elts.as_ptr(), elts.len() as c_uint,
841 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
843 llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
847 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
849 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
853 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
854 C_bytes_in_context(cx.llcx(), bytes)
857 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
859 let ptr = bytes.as_ptr() as *const c_char;
860 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
864 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
867 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
869 debug!("const_get_elt(v={}, us={}, r={})",
870 cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
876 pub fn is_const(v: ValueRef) -> bool {
878 llvm::LLVMIsConstant(v) == True
882 pub fn const_to_int(v: ValueRef) -> i64 {
884 llvm::LLVMConstIntGetSExtValue(v)
888 pub fn const_to_uint(v: ValueRef) -> u64 {
890 llvm::LLVMConstIntGetZExtValue(v)
894 pub fn is_undef(val: ValueRef) -> bool {
896 llvm::LLVMIsUndef(val) != False
900 #[allow(dead_code)] // potentially useful
901 pub fn is_null(val: ValueRef) -> bool {
903 llvm::LLVMIsNull(val) != False
907 pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
908 bcx.fcx.monomorphize(&t)
911 pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> {
913 let t = ty::node_id_to_type(tcx, id);
914 monomorphize_type(bcx, t)
917 pub fn expr_ty<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
918 node_id_type(bcx, ex.id)
921 pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
922 monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
925 /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we
926 /// do not (necessarily) resolve all nested obligations on the impl. Note that type check should
927 /// guarantee to us that all nested obligations *could be* resolved if we wanted to.
928 pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
930 trait_ref: ty::PolyTraitRef<'tcx>)
931 -> traits::Vtable<'tcx, ()>
935 // Remove any references to regions; this helps improve caching.
936 let trait_ref = ty_fold::erase_regions(tcx, trait_ref);
938 // First check the cache.
939 match ccx.trait_cache().borrow().get(&trait_ref) {
941 info!("Cache hit: {}", trait_ref.repr(ccx.tcx()));
942 return (*vtable).clone();
947 debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx()));
949 ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id());
950 let infcx = infer::new_infer_ctxt(tcx);
952 // Do the initial selection for the obligation. This yields the
953 // shallow result we are looking for -- that is, what specific impl.
954 let typer = NormalizingUnboxedClosureTyper::new(tcx);
955 let mut selcx = traits::SelectionContext::new(&infcx, &typer);
956 let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
957 trait_ref.to_poly_trait_predicate());
958 let selection = match selcx.select(&obligation) {
959 Ok(Some(selection)) => selection,
961 // Ambiguity can happen when monomorphizing during trans
962 // expands to some humongo type that never occurred
963 // statically -- this humongo type can then overflow,
964 // leading to an ambiguous result. So report this as an
965 // overflow bug, since I believe this is the only case
966 // where ambiguity can result.
967 debug!("Encountered ambiguity selecting `{}` during trans, \
968 presuming due to overflow",
969 trait_ref.repr(tcx));
970 ccx.sess().span_fatal(
972 "reached the recursion limit during monomorphization");
977 format!("Encountered error `{}` selecting `{}` during trans",
979 trait_ref.repr(tcx))[])
983 // Currently, we use a fulfillment context to completely resolve
984 // all nested obligations. This is because they can inform the
985 // inference of the impl's type parameters.
986 let mut fulfill_cx = traits::FulfillmentContext::new();
987 let vtable = selection.map_move_nested(|predicate| {
988 fulfill_cx.register_predicate_obligation(&infcx, predicate);
990 let vtable = drain_fulfillment_cx(span, &infcx, &mut fulfill_cx, &vtable);
992 info!("Cache miss: {}", trait_ref.repr(ccx.tcx()));
993 ccx.trait_cache().borrow_mut().insert(trait_ref,
999 pub struct NormalizingUnboxedClosureTyper<'a,'tcx:'a> {
1000 param_env: ty::ParameterEnvironment<'a, 'tcx>
1003 impl<'a,'tcx> NormalizingUnboxedClosureTyper<'a,'tcx> {
1004 pub fn new(tcx: &'a ty::ctxt<'tcx>) -> NormalizingUnboxedClosureTyper<'a,'tcx> {
1005 // Parameter environment is used to give details about type parameters,
1006 // but since we are in trans, everything is fully monomorphized.
1007 NormalizingUnboxedClosureTyper { param_env: ty::empty_parameter_environment(tcx) }
1011 impl<'a,'tcx> ty::UnboxedClosureTyper<'tcx> for NormalizingUnboxedClosureTyper<'a,'tcx> {
1012 fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1016 fn unboxed_closure_kind(&self,
1018 -> ty::UnboxedClosureKind
1020 self.param_env.tcx.unboxed_closure_kind(def_id)
1023 fn unboxed_closure_type(&self,
1025 substs: &subst::Substs<'tcx>)
1026 -> ty::ClosureTy<'tcx>
1028 // the substitutions in `substs` are already monomorphized,
1029 // but we still must normalize associated types
1030 let closure_ty = self.param_env.tcx.unboxed_closure_type(def_id, substs);
1031 monomorphize::normalize_associated_type(self.param_env.tcx, &closure_ty)
1034 fn unboxed_closure_upvars(&self,
1036 substs: &Substs<'tcx>)
1037 -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>>
1039 // the substitutions in `substs` are already monomorphized,
1040 // but we still must normalize associated types
1041 let result = ty::unboxed_closure_upvars(&self.param_env, def_id, substs);
1042 monomorphize::normalize_associated_type(self.param_env.tcx, &result)
1046 pub fn drain_fulfillment_cx<'a,'tcx,T>(span: Span,
1047 infcx: &infer::InferCtxt<'a,'tcx>,
1048 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
1051 where T : TypeFoldable<'tcx> + Repr<'tcx>
1053 debug!("drain_fulfillment_cx(result={})",
1054 result.repr(infcx.tcx));
1056 // In principle, we only need to do this so long as `result`
1057 // contains unbound type parameters. It could be a slight
1058 // optimization to stop iterating early.
1059 let typer = NormalizingUnboxedClosureTyper::new(infcx.tcx);
1060 match fulfill_cx.select_all_or_error(infcx, &typer) {
1063 if errors.iter().all(|e| e.is_overflow()) {
1064 // See Ok(None) case above.
1065 infcx.tcx.sess.span_fatal(
1067 "reached the recursion limit during monomorphization");
1069 infcx.tcx.sess.span_bug(
1071 format!("Encountered errors `{}` fulfilling during trans",
1072 errors.repr(infcx.tcx))[]);
1077 // Use freshen to simultaneously replace all type variables with
1078 // their bindings and replace all regions with 'static. This is
1079 // sort of overkill because we do not expect there to be any
1080 // unbound type variables, hence no `TyFresh` types should ever be
1082 result.fold_with(&mut infcx.freshener())
1085 // Key used to lookup values supplied for type parameters in an expr.
1086 #[derive(Copy, PartialEq, Show)]
1087 pub enum ExprOrMethodCall {
1088 // Type parameters for a path like `None::<int>`
1089 ExprId(ast::NodeId),
1091 // Type parameters for a method call like `a.foo::<int>()`
1092 MethodCallKey(ty::MethodCall)
1095 pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1096 node: ExprOrMethodCall,
1097 param_substs: &subst::Substs<'tcx>)
1098 -> subst::Substs<'tcx> {
1099 let tcx = ccx.tcx();
1101 let substs = match node {
1103 ty::node_id_item_substs(tcx, id).substs
1105 MethodCallKey(method_call) => {
1106 (*tcx.method_map.borrow())[method_call].substs.clone()
1110 if substs.types.any(|t| ty::type_needs_infer(*t)) {
1111 tcx.sess.bug(format!("type parameters for node {} include inference types: {}",
1112 node, substs.repr(tcx))[]);
1115 monomorphize::apply_param_substs(tcx,
1117 &substs.erase_regions())
1120 pub fn langcall(bcx: Block,
1125 match bcx.tcx().lang_items.require(li) {
1128 let msg = format!("{} {}", msg, s);
1130 Some(span) => bcx.tcx().sess.span_fatal(span, msg[]),
1131 None => bcx.tcx().sess.fatal(msg[]),