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::c_str::ToCStr;
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 "return".with_c_str(|buf| {
405 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn, buf)
410 self.llreturn.get().unwrap()
413 pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>,
414 output: ty::FnOutput<'tcx>,
415 name: &str) -> ValueRef {
416 if self.needs_ret_allocas {
417 base::alloca_no_lifetime(bcx, match output {
418 ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type),
419 ty::FnDiverging => Type::void(bcx.ccx())
422 self.llretslotptr.get().unwrap()
426 pub fn new_block(&'a self,
429 opt_node_id: Option<ast::NodeId>)
432 let llbb = name.with_c_str(|buf| {
433 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
437 BlockS::new(llbb, is_lpad, opt_node_id, self)
441 pub fn new_id_block(&'a self,
443 node_id: ast::NodeId)
445 self.new_block(false, name, Some(node_id))
448 pub fn new_temp_block(&'a self,
451 self.new_block(false, name, None)
454 pub fn join_blocks(&'a self,
456 in_cxs: &[Block<'a, 'tcx>])
458 let out = self.new_id_block("join", id);
459 let mut reachable = false;
460 for bcx in in_cxs.iter() {
461 if !bcx.unreachable.get() {
462 build::Br(*bcx, out.llbb);
467 build::Unreachable(out);
472 pub fn monomorphize<T>(&self, value: &T) -> T
473 where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
475 monomorphize::apply_param_substs(self.ccx.tcx(),
481 // Basic block context. We create a block context for each basic block
482 // (single-entry, single-exit sequence of instructions) we generate from Rust
483 // code. Each basic block we generate is attached to a function, typically
484 // with many basic blocks per function. All the basic blocks attached to a
485 // function are organized as a directed graph.
486 pub struct BlockS<'blk, 'tcx: 'blk> {
487 // The BasicBlockRef returned from a call to
488 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
489 // block to the function pointed to by llfn. We insert
490 // instructions into that block by way of this block context.
491 // The block pointing to this one in the function's digraph.
492 pub llbb: BasicBlockRef,
493 pub terminated: Cell<bool>,
494 pub unreachable: Cell<bool>,
496 // Is this block part of a landing pad?
499 // AST node-id associated with this block, if any. Used for
500 // debugging purposes only.
501 pub opt_node_id: Option<ast::NodeId>,
503 // The function context for the function to which this block is
505 pub fcx: &'blk FunctionContext<'blk, 'tcx>,
508 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
510 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
511 pub fn new(llbb: BasicBlockRef,
513 opt_node_id: Option<ast::NodeId>,
514 fcx: &'blk FunctionContext<'blk, 'tcx>)
515 -> Block<'blk, 'tcx> {
516 fcx.block_arena.alloc(BlockS {
518 terminated: Cell::new(false),
519 unreachable: Cell::new(false),
521 opt_node_id: opt_node_id,
526 pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
529 pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
532 pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
534 pub fn ident(&self, ident: Ident) -> String {
535 token::get_ident(ident).get().to_string()
538 pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
539 self.tcx().map.node_to_string(id).to_string()
542 pub fn expr_to_string(&self, e: &ast::Expr) -> String {
546 pub fn def(&self, nid: ast::NodeId) -> def::Def {
547 match self.tcx().def_map.borrow().get(&nid) {
548 Some(v) => v.clone(),
550 self.tcx().sess.bug(format!(
551 "no def associated with node id {}", nid)[]);
556 pub fn val_to_string(&self, val: ValueRef) -> String {
557 self.ccx().tn().val_to_string(val)
560 pub fn llty_str(&self, ty: Type) -> String {
561 self.ccx().tn().type_to_string(ty)
564 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
568 pub fn to_str(&self) -> String {
569 format!("[block {:p}]", self)
572 pub fn monomorphize<T>(&self, value: &T) -> T
573 where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone
575 monomorphize::apply_param_substs(self.tcx(),
576 self.fcx.param_substs,
581 impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> {
582 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
586 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
587 Ok(node_id_type(self, id))
590 fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult<Ty<'tcx>> {
591 Ok(expr_ty_adjusted(self, expr))
594 fn node_method_ty(&self, method_call: ty::MethodCall) -> Option<Ty<'tcx>> {
599 .map(|method| monomorphize_type(self, method.ty))
602 fn node_method_origin(&self, method_call: ty::MethodCall)
603 -> Option<ty::MethodOrigin<'tcx>>
609 .map(|method| method.origin.clone())
612 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
613 &self.tcx().adjustments
616 fn is_method_call(&self, id: ast::NodeId) -> bool {
617 self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id))
620 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
621 self.tcx().region_maps.temporary_scope(rvalue_id)
624 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option<ty::UpvarBorrow> {
625 Some(self.tcx().upvar_borrow_map.borrow()[upvar_id].clone())
628 fn capture_mode(&self, closure_expr_id: ast::NodeId)
629 -> ast::CaptureClause {
630 self.tcx().capture_modes.borrow()[closure_expr_id].clone()
633 fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool {
634 self.fcx.param_env.type_moves_by_default(span, ty)
638 impl<'blk, 'tcx> ty::UnboxedClosureTyper<'tcx> for BlockS<'blk, 'tcx> {
639 fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx> {
643 fn unboxed_closure_kind(&self,
645 -> ty::UnboxedClosureKind
647 let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
648 typer.unboxed_closure_kind(def_id)
651 fn unboxed_closure_type(&self,
653 substs: &subst::Substs<'tcx>)
654 -> ty::ClosureTy<'tcx>
656 let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
657 typer.unboxed_closure_type(def_id, substs)
660 fn unboxed_closure_upvars(&self,
662 substs: &Substs<'tcx>)
663 -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>>
665 let typer = NormalizingUnboxedClosureTyper::new(self.tcx());
666 typer.unboxed_closure_upvars(def_id, substs)
670 pub struct Result<'blk, 'tcx: 'blk> {
671 pub bcx: Block<'blk, 'tcx>,
675 impl<'b, 'tcx> Result<'b, 'tcx> {
676 pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
684 pub fn val_ty(v: ValueRef) -> Type {
686 Type::from_ref(llvm::LLVMTypeOf(v))
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 s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
715 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
716 C_struct(ccx, &[], false)
719 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
720 C_integral(Type::i1(ccx), val as u64, false)
723 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
724 C_integral(Type::i32(ccx), i as u64, true)
727 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
728 C_integral(Type::i64(ccx), i as u64, true)
731 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
732 C_integral(Type::i64(ccx), i, false)
735 pub fn C_int<I: AsI64>(ccx: &CrateContext, i: I) -> ValueRef {
738 match machine::llbitsize_of_real(ccx, ccx.int_type()) {
739 32 => assert!(v < (1<<31) && v >= -(1<<31)),
741 n => panic!("unsupported target size: {}", n)
744 C_integral(ccx.int_type(), v as u64, true)
747 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
750 match machine::llbitsize_of_real(ccx, ccx.int_type()) {
751 32 => assert!(v < (1<<32)),
753 n => panic!("unsupported target size: {}", n)
756 C_integral(ccx.int_type(), v, false)
759 pub trait AsI64 { fn as_i64(self) -> i64; }
760 pub trait AsU64 { fn as_u64(self) -> u64; }
762 // FIXME: remove the intptr conversions, because they
763 // are host-architecture-dependent
764 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
765 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
766 impl AsI64 for int { fn as_i64(self) -> i64 { self as i64 }}
768 impl AsU64 for u64 { fn as_u64(self) -> u64 { self as u64 }}
769 impl AsU64 for u32 { fn as_u64(self) -> u64 { self as u64 }}
770 impl AsU64 for uint { fn as_u64(self) -> u64 { self as u64 }}
772 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
773 C_integral(Type::i8(ccx), i as u64, false)
777 // This is a 'c-like' raw string, which differs from
778 // our boxed-and-length-annotated strings.
779 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
781 match cx.const_cstr_cache().borrow().get(&s) {
782 Some(&llval) => return llval,
786 let sc = llvm::LLVMConstStringInContext(cx.llcx(),
787 s.get().as_ptr() as *const c_char,
788 s.get().len() as c_uint,
789 !null_terminated as Bool);
791 let gsym = token::gensym("str");
792 let g = format!("str{}", gsym.uint()).with_c_str(|buf| {
793 llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf)
795 llvm::LLVMSetInitializer(g, sc);
796 llvm::LLVMSetGlobalConstant(g, True);
797 llvm::SetLinkage(g, llvm::InternalLinkage);
799 cx.const_cstr_cache().borrow_mut().insert(s, g);
804 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
805 // you will be kicked off fast isel. See issue #4352 for an example of this.
806 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
807 let len = s.get().len();
808 let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
809 C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
812 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
814 let len = data.len();
815 let lldata = C_bytes(cx, data);
817 let gsym = token::gensym("binary");
818 let g = format!("binary{}", gsym.uint()).with_c_str(|buf| {
819 llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), buf)
821 llvm::LLVMSetInitializer(g, lldata);
822 llvm::LLVMSetGlobalConstant(g, True);
823 llvm::SetLinkage(g, llvm::InternalLinkage);
825 let cs = consts::ptrcast(g, Type::i8p(cx));
826 C_struct(cx, &[cs, C_uint(cx, len)], false)
830 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
831 C_struct_in_context(cx.llcx(), elts, packed)
834 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
836 llvm::LLVMConstStructInContext(llcx,
837 elts.as_ptr(), elts.len() as c_uint,
842 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
844 llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
848 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
850 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
854 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
855 C_bytes_in_context(cx.llcx(), bytes)
858 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
860 let ptr = bytes.as_ptr() as *const c_char;
861 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
865 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
868 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
870 debug!("const_get_elt(v={}, us={}, r={})",
871 cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
877 pub fn is_const(v: ValueRef) -> bool {
879 llvm::LLVMIsConstant(v) == True
883 pub fn const_to_int(v: ValueRef) -> i64 {
885 llvm::LLVMConstIntGetSExtValue(v)
889 pub fn const_to_uint(v: ValueRef) -> u64 {
891 llvm::LLVMConstIntGetZExtValue(v)
895 pub fn is_undef(val: ValueRef) -> bool {
897 llvm::LLVMIsUndef(val) != False
901 #[allow(dead_code)] // potentially useful
902 pub fn is_null(val: ValueRef) -> bool {
904 llvm::LLVMIsNull(val) != False
908 pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
909 bcx.fcx.monomorphize(&t)
912 pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> {
914 let t = ty::node_id_to_type(tcx, id);
915 monomorphize_type(bcx, t)
918 pub fn expr_ty<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
919 node_id_type(bcx, ex.id)
922 pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
923 monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
926 /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we
927 /// do not (necessarily) resolve all nested obligations on the impl. Note that type check should
928 /// guarantee to us that all nested obligations *could be* resolved if we wanted to.
929 pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
931 trait_ref: ty::PolyTraitRef<'tcx>)
932 -> traits::Vtable<'tcx, ()>
936 // Remove any references to regions; this helps improve caching.
937 let trait_ref = ty_fold::erase_regions(tcx, trait_ref);
939 // First check the cache.
940 match ccx.trait_cache().borrow().get(&trait_ref) {
942 info!("Cache hit: {}", trait_ref.repr(ccx.tcx()));
943 return (*vtable).clone();
948 debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx()));
950 ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id());
951 let infcx = infer::new_infer_ctxt(tcx);
953 // Do the initial selection for the obligation. This yields the
954 // shallow result we are looking for -- that is, what specific impl.
955 let typer = NormalizingUnboxedClosureTyper::new(tcx);
956 let mut selcx = traits::SelectionContext::new(&infcx, &typer);
957 let obligation = traits::Obligation::new(traits::ObligationCause::dummy(),
958 trait_ref.to_poly_trait_predicate());
959 let selection = match selcx.select(&obligation) {
960 Ok(Some(selection)) => selection,
962 // Ambiguity can happen when monomorphizing during trans
963 // expands to some humongo type that never occurred
964 // statically -- this humongo type can then overflow,
965 // leading to an ambiguous result. So report this as an
966 // overflow bug, since I believe this is the only case
967 // where ambiguity can result.
968 debug!("Encountered ambiguity selecting `{}` during trans, \
969 presuming due to overflow",
970 trait_ref.repr(tcx));
971 ccx.sess().span_fatal(
973 "reached the recursion limit during monomorphization");
978 format!("Encountered error `{}` selecting `{}` during trans",
980 trait_ref.repr(tcx))[])
984 // Currently, we use a fulfillment context to completely resolve
985 // all nested obligations. This is because they can inform the
986 // inference of the impl's type parameters.
987 let mut fulfill_cx = traits::FulfillmentContext::new();
988 let vtable = selection.map_move_nested(|predicate| {
989 fulfill_cx.register_predicate_obligation(&infcx, predicate);
991 let vtable = drain_fulfillment_cx(span, &infcx, &mut fulfill_cx, &vtable);
993 info!("Cache miss: {}", trait_ref.repr(ccx.tcx()));
994 ccx.trait_cache().borrow_mut().insert(trait_ref,
1000 pub struct NormalizingUnboxedClosureTyper<'a,'tcx:'a> {
1001 param_env: ty::ParameterEnvironment<'a, 'tcx>
1004 impl<'a,'tcx> NormalizingUnboxedClosureTyper<'a,'tcx> {
1005 pub fn new(tcx: &'a ty::ctxt<'tcx>) -> NormalizingUnboxedClosureTyper<'a,'tcx> {
1006 // Parameter environment is used to give details about type parameters,
1007 // but since we are in trans, everything is fully monomorphized.
1008 NormalizingUnboxedClosureTyper { param_env: ty::empty_parameter_environment(tcx) }
1012 impl<'a,'tcx> ty::UnboxedClosureTyper<'tcx> for NormalizingUnboxedClosureTyper<'a,'tcx> {
1013 fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> {
1017 fn unboxed_closure_kind(&self,
1019 -> ty::UnboxedClosureKind
1021 self.param_env.tcx.unboxed_closure_kind(def_id)
1024 fn unboxed_closure_type(&self,
1026 substs: &subst::Substs<'tcx>)
1027 -> ty::ClosureTy<'tcx>
1029 // the substitutions in `substs` are already monomorphized,
1030 // but we still must normalize associated types
1031 let closure_ty = self.param_env.tcx.unboxed_closure_type(def_id, substs);
1032 monomorphize::normalize_associated_type(self.param_env.tcx, &closure_ty)
1035 fn unboxed_closure_upvars(&self,
1037 substs: &Substs<'tcx>)
1038 -> Option<Vec<ty::UnboxedClosureUpvar<'tcx>>>
1040 // the substitutions in `substs` are already monomorphized,
1041 // but we still must normalize associated types
1042 let result = ty::unboxed_closure_upvars(&self.param_env, def_id, substs);
1043 monomorphize::normalize_associated_type(self.param_env.tcx, &result)
1047 pub fn drain_fulfillment_cx<'a,'tcx,T>(span: Span,
1048 infcx: &infer::InferCtxt<'a,'tcx>,
1049 fulfill_cx: &mut traits::FulfillmentContext<'tcx>,
1052 where T : TypeFoldable<'tcx> + Repr<'tcx>
1054 debug!("drain_fulfillment_cx(result={})",
1055 result.repr(infcx.tcx));
1057 // In principle, we only need to do this so long as `result`
1058 // contains unbound type parameters. It could be a slight
1059 // optimization to stop iterating early.
1060 let typer = NormalizingUnboxedClosureTyper::new(infcx.tcx);
1061 match fulfill_cx.select_all_or_error(infcx, &typer) {
1064 if errors.iter().all(|e| e.is_overflow()) {
1065 // See Ok(None) case above.
1066 infcx.tcx.sess.span_fatal(
1068 "reached the recursion limit during monomorphization");
1070 infcx.tcx.sess.span_bug(
1072 format!("Encountered errors `{}` fulfilling during trans",
1073 errors.repr(infcx.tcx))[]);
1078 // Use freshen to simultaneously replace all type variables with
1079 // their bindings and replace all regions with 'static. This is
1080 // sort of overkill because we do not expect there to be any
1081 // unbound type variables, hence no `TyFresh` types should ever be
1083 result.fold_with(&mut infcx.freshener())
1086 // Key used to lookup values supplied for type parameters in an expr.
1087 #[derive(Copy, PartialEq, Show)]
1088 pub enum ExprOrMethodCall {
1089 // Type parameters for a path like `None::<int>`
1090 ExprId(ast::NodeId),
1092 // Type parameters for a method call like `a.foo::<int>()`
1093 MethodCallKey(ty::MethodCall)
1096 pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1097 node: ExprOrMethodCall,
1098 param_substs: &subst::Substs<'tcx>)
1099 -> subst::Substs<'tcx> {
1100 let tcx = ccx.tcx();
1102 let substs = match node {
1104 ty::node_id_item_substs(tcx, id).substs
1106 MethodCallKey(method_call) => {
1107 (*tcx.method_map.borrow())[method_call].substs.clone()
1111 if substs.types.any(|t| ty::type_needs_infer(*t)) {
1112 tcx.sess.bug(format!("type parameters for node {} include inference types: {}",
1113 node, substs.repr(tcx))[]);
1116 monomorphize::apply_param_substs(tcx,
1118 &substs.erase_regions())
1121 pub fn langcall(bcx: Block,
1126 match bcx.tcx().lang_items.require(li) {
1129 let msg = format!("{} {}", msg, s);
1131 Some(span) => bcx.tcx().sess.span_fatal(span, msg[]),
1132 None => bcx.tcx().sess.fatal(msg[]),