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};
22 use middle::lang_items::LangItem;
23 use middle::mem_categorization as mc;
26 use middle::subst::{Subst, Substs};
33 use trans::type_::Type;
36 use middle::ty::{mod, Ty};
38 use middle::ty_fold::TypeFoldable;
40 use middle::typeck::infer;
41 use util::ppaux::Repr;
42 use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};
44 use arena::TypedArena;
45 use libc::{c_uint, c_char};
46 use std::c_str::ToCStr;
47 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;
57 pub use trans::context::CrateContext;
59 fn type_is_newtype_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
60 ty: Ty<'tcx>) -> bool {
62 ty::ty_struct(def_id, ref substs) => {
63 let fields = ty::struct_fields(ccx.tcx(), def_id, substs);
66 token::special_idents::unnamed_field.name &&
67 type_is_immediate(ccx, fields[0].mt.ty)
73 pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
74 use trans::machine::llsize_of_alloc;
75 use trans::type_of::sizing_type_of;
78 let simple = ty::type_is_scalar(ty) ||
79 ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
80 type_is_newtype_immediate(ccx, ty) ||
81 ty::type_is_simd(tcx, ty);
82 if simple && !ty::type_is_fat_ptr(tcx, ty) {
85 if !ty::type_is_sized(tcx, ty) {
89 ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) |
90 ty::ty_unboxed_closure(..) => {
91 let llty = sizing_type_of(ccx, ty);
92 llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type())
94 _ => type_is_zero_size(ccx, ty)
98 pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
100 * Identify types which have size zero at runtime.
103 use trans::machine::llsize_of_alloc;
104 use trans::type_of::sizing_type_of;
105 let llty = sizing_type_of(ccx, ty);
106 llsize_of_alloc(ccx, llty) == 0
109 pub fn return_type_is_void(ccx: &CrateContext, ty: Ty) -> bool {
111 * Identifies types which we declare to be equivalent to `void`
112 * in C for the purpose of function return types. These are
113 * `()`, bot, and uninhabited enums. Note that all such types
114 * are also zero-size, but not all zero-size types use a `void`
115 * return type (in order to aid with C ABI compatibility).
118 ty::type_is_nil(ty) || ty::type_is_empty(ccx.tcx(), ty)
121 /// Generates a unique symbol based off the name given. This is used to create
122 /// unique symbols for things like closures.
123 pub fn gensym_name(name: &str) -> PathElem {
124 let num = token::gensym(name).uint();
125 // use one colon which will get translated to a period by the mangler, and
126 // we're guaranteed that `num` is globally unique for this crate.
127 PathName(token::gensym(format!("{}:{}", name, num).as_slice()))
130 pub struct tydesc_info<'tcx> {
132 pub tydesc: ValueRef,
139 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
141 * An "extern" is an LLVM symbol we wind up emitting an undefined external
142 * reference to. This means "we don't have the thing in this compilation unit,
143 * please make sure you link it in at runtime". This could be a reference to
144 * C code found in a C library, or rust code found in a rust crate.
146 * Most "externs" are implicitly declared (automatically) as a result of a
147 * user declaring an extern _module_ dependency; this causes the rust driver
148 * to locate an extern crate, scan its compilation metadata, and emit extern
149 * declarations for any symbols used by the declaring crate.
151 * A "foreign" is an extern that references C (or other non-rust ABI) code.
152 * There is no metadata to scan for extern references so in these cases either
153 * a header-digester like bindgen, or manual function prototypes, have to
154 * serve as declarators. So these are usually given explicitly as prototype
155 * declarations, in rust code, with ABI attributes on them noting which ABI to
158 * An "upcall" is a foreign call generated by the compiler (not corresponding
159 * to any user-written call in the code) into the runtime library, to perform
160 * some helper task such as bringing a task to life, allocating memory, etc.
164 pub struct NodeInfo {
169 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
170 NodeInfo { id: expr.id, span: expr.span }
173 pub struct BuilderRef_res {
177 impl Drop for BuilderRef_res {
180 llvm::LLVMDisposeBuilder(self.b);
185 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
191 pub type ExternMap = FnvHashMap<String, ValueRef>;
193 pub fn validate_substs(substs: &Substs) {
194 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
197 // work around bizarre resolve errors
198 pub type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
199 pub type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
201 // Function context. Every LLVM function we create will have one of
203 pub struct FunctionContext<'a, 'tcx: 'a> {
204 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
205 // address of the first instruction in the sequence of
206 // instructions for this function that will go in the .text
207 // section of the executable we're generating.
210 // The environment argument in a closure.
211 pub llenv: Option<ValueRef>,
213 // A pointer to where to store the return value. If the return type is
214 // immediate, this points to an alloca in the function. Otherwise, it's a
215 // pointer to the hidden first parameter of the function. After function
216 // construction, this should always be Some.
217 pub llretslotptr: Cell<Option<ValueRef>>,
219 // These pub elements: "hoisted basic blocks" containing
220 // administrative activities that have to happen in only one place in
221 // the function, due to LLVM's quirks.
222 // A marker for the place where we want to insert the function's static
223 // allocas, so that LLVM will coalesce them into a single alloca call.
224 pub alloca_insert_pt: Cell<Option<ValueRef>>,
225 pub llreturn: Cell<Option<BasicBlockRef>>,
227 // If the function has any nested return's, including something like:
228 // fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then
229 // we use a separate alloca for each return
230 pub needs_ret_allocas: bool,
232 // The a value alloca'd for calls to upcalls.rust_personality. Used when
233 // outputting the resume instruction.
234 pub personality: Cell<Option<ValueRef>>,
236 // True if the caller expects this fn to use the out pointer to
237 // return. Either way, your code should write into the slot llretslotptr
238 // points to, but if this value is false, that slot will be a local alloca.
239 pub caller_expects_out_pointer: bool,
241 // Maps the DefId's for local variables to the allocas created for
242 // them in llallocas.
243 pub lllocals: RefCell<NodeMap<LvalueDatum<'tcx>>>,
245 // Same as above, but for closure upvars
246 pub llupvars: RefCell<NodeMap<ValueRef>>,
248 // The NodeId of the function, or -1 if it doesn't correspond to
249 // a user-defined function.
252 // If this function is being monomorphized, this contains the type
253 // substitutions used.
254 pub param_substs: &'a Substs<'tcx>,
256 // The source span and nesting context where this function comes from, for
257 // error reporting and symbol generation.
258 pub span: Option<Span>,
260 // The arena that blocks are allocated from.
261 pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>,
263 // This function's enclosing crate context.
264 pub ccx: &'a CrateContext<'a, 'tcx>,
266 // Used and maintained by the debuginfo module.
267 pub debug_context: debuginfo::FunctionDebugContext,
270 pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>,
273 impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
274 pub fn arg_pos(&self, arg: uint) -> uint {
275 let arg = self.env_arg_pos() + arg;
276 if self.llenv.is_some() {
283 pub fn out_arg_pos(&self) -> uint {
284 assert!(self.caller_expects_out_pointer);
288 pub fn env_arg_pos(&self) -> uint {
289 if self.caller_expects_out_pointer {
296 pub fn cleanup(&self) {
298 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
304 pub fn get_llreturn(&self) -> BasicBlockRef {
305 if self.llreturn.get().is_none() {
307 self.llreturn.set(Some(unsafe {
308 "return".with_c_str(|buf| {
309 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn, buf)
314 self.llreturn.get().unwrap()
317 pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>,
318 output: ty::FnOutput<'tcx>,
319 name: &str) -> ValueRef {
320 if self.needs_ret_allocas {
321 base::alloca_no_lifetime(bcx, match output {
322 ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type),
323 ty::FnDiverging => Type::void(bcx.ccx())
326 self.llretslotptr.get().unwrap()
330 pub fn new_block(&'a self,
333 opt_node_id: Option<ast::NodeId>)
336 let llbb = name.with_c_str(|buf| {
337 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
341 BlockS::new(llbb, is_lpad, opt_node_id, self)
345 pub fn new_id_block(&'a self,
347 node_id: ast::NodeId)
349 self.new_block(false, name, Some(node_id))
352 pub fn new_temp_block(&'a self,
355 self.new_block(false, name, None)
358 pub fn join_blocks(&'a self,
360 in_cxs: &[Block<'a, 'tcx>])
362 let out = self.new_id_block("join", id);
363 let mut reachable = false;
364 for bcx in in_cxs.iter() {
365 if !bcx.unreachable.get() {
366 build::Br(*bcx, out.llbb);
371 build::Unreachable(out);
377 // Basic block context. We create a block context for each basic block
378 // (single-entry, single-exit sequence of instructions) we generate from Rust
379 // code. Each basic block we generate is attached to a function, typically
380 // with many basic blocks per function. All the basic blocks attached to a
381 // function are organized as a directed graph.
382 pub struct BlockS<'blk, 'tcx: 'blk> {
383 // The BasicBlockRef returned from a call to
384 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
385 // block to the function pointed to by llfn. We insert
386 // instructions into that block by way of this block context.
387 // The block pointing to this one in the function's digraph.
388 pub llbb: BasicBlockRef,
389 pub terminated: Cell<bool>,
390 pub unreachable: Cell<bool>,
392 // Is this block part of a landing pad?
395 // AST node-id associated with this block, if any. Used for
396 // debugging purposes only.
397 pub opt_node_id: Option<ast::NodeId>,
399 // The function context for the function to which this block is
401 pub fcx: &'blk FunctionContext<'blk, 'tcx>,
404 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
406 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
407 pub fn new(llbb: BasicBlockRef,
409 opt_node_id: Option<ast::NodeId>,
410 fcx: &'blk FunctionContext<'blk, 'tcx>)
411 -> Block<'blk, 'tcx> {
412 fcx.block_arena.alloc(BlockS {
414 terminated: Cell::new(false),
415 unreachable: Cell::new(false),
417 opt_node_id: opt_node_id,
422 pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
425 pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
428 pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
430 pub fn ident(&self, ident: Ident) -> String {
431 token::get_ident(ident).get().to_string()
434 pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
435 self.tcx().map.node_to_string(id).to_string()
438 pub fn expr_to_string(&self, e: &ast::Expr) -> String {
442 pub fn def(&self, nid: ast::NodeId) -> def::Def {
443 match self.tcx().def_map.borrow().get(&nid) {
444 Some(v) => v.clone(),
446 self.tcx().sess.bug(format!(
447 "no def associated with node id {}", nid).as_slice());
452 pub fn val_to_string(&self, val: ValueRef) -> String {
453 self.ccx().tn().val_to_string(val)
456 pub fn llty_str(&self, ty: Type) -> String {
457 self.ccx().tn().type_to_string(ty)
460 pub fn ty_to_string(&self, t: Ty<'tcx>) -> String {
464 pub fn to_str(&self) -> String {
465 format!("[block {:p}]", self)
469 impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> {
470 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
474 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<Ty<'tcx>> {
475 Ok(node_id_type(self, id))
478 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<Ty<'tcx>> {
483 .map(|method| monomorphize_type(self, method.ty))
486 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment<'tcx>>> {
487 &self.tcx().adjustments
490 fn is_method_call(&self, id: ast::NodeId) -> bool {
491 self.tcx().method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
494 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<region::CodeExtent> {
495 self.tcx().region_maps.temporary_scope(rvalue_id)
498 fn unboxed_closures<'a>(&'a self)
499 -> &'a RefCell<DefIdMap<ty::UnboxedClosure<'tcx>>> {
500 &self.tcx().unboxed_closures
503 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
504 self.tcx().upvar_borrow_map.borrow()[upvar_id].clone()
507 fn capture_mode(&self, closure_expr_id: ast::NodeId)
508 -> ast::CaptureClause {
509 self.tcx().capture_modes.borrow()[closure_expr_id].clone()
513 pub struct Result<'blk, 'tcx: 'blk> {
514 pub bcx: Block<'blk, 'tcx>,
518 impl<'b, 'tcx> Result<'b, 'tcx> {
519 pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
527 pub fn val_ty(v: ValueRef) -> Type {
529 Type::from_ref(llvm::LLVMTypeOf(v))
533 // LLVM constant constructors.
534 pub fn C_null(t: Type) -> ValueRef {
536 llvm::LLVMConstNull(t.to_ref())
540 pub fn C_undef(t: Type) -> ValueRef {
542 llvm::LLVMGetUndef(t.to_ref())
546 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
548 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
552 pub fn C_floating(s: &str, t: Type) -> ValueRef {
554 s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
558 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
559 C_struct(ccx, &[], false)
562 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
563 C_integral(Type::i1(ccx), val as u64, false)
566 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
567 C_integral(Type::i32(ccx), i as u64, true)
570 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
571 C_integral(Type::i64(ccx), i as u64, true)
574 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
575 C_integral(Type::i64(ccx), i, false)
578 pub fn C_int<I: AsI64>(ccx: &CrateContext, i: I) -> ValueRef {
581 match machine::llbitsize_of_real(ccx, ccx.int_type()) {
582 32 => assert!(v < (1<<31) && v >= -(1<<31)),
584 n => panic!("unsupported target size: {}", n)
587 C_integral(ccx.int_type(), v as u64, true)
590 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
593 match machine::llbitsize_of_real(ccx, ccx.int_type()) {
594 32 => assert!(v < (1<<32)),
596 n => panic!("unsupported target size: {}", n)
599 C_integral(ccx.int_type(), v, false)
602 pub trait AsI64 { fn as_i64(self) -> i64; }
603 pub trait AsU64 { fn as_u64(self) -> u64; }
605 // FIXME: remove the intptr conversions, because they
606 // are host-architecture-dependent
607 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
608 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
609 impl AsI64 for int { fn as_i64(self) -> i64 { self as i64 }}
611 impl AsU64 for u64 { fn as_u64(self) -> u64 { self as u64 }}
612 impl AsU64 for u32 { fn as_u64(self) -> u64 { self as u64 }}
613 impl AsU64 for uint { fn as_u64(self) -> u64 { self as u64 }}
615 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
616 C_integral(Type::i8(ccx), i as u64, false)
620 // This is a 'c-like' raw string, which differs from
621 // our boxed-and-length-annotated strings.
622 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
624 match cx.const_cstr_cache().borrow().get(&s) {
625 Some(&llval) => return llval,
629 let sc = llvm::LLVMConstStringInContext(cx.llcx(),
630 s.get().as_ptr() as *const c_char,
631 s.get().len() as c_uint,
632 !null_terminated as Bool);
634 let gsym = token::gensym("str");
635 let g = format!("str{}", gsym.uint()).with_c_str(|buf| {
636 llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf)
638 llvm::LLVMSetInitializer(g, sc);
639 llvm::LLVMSetGlobalConstant(g, True);
640 llvm::SetLinkage(g, llvm::InternalLinkage);
642 cx.const_cstr_cache().borrow_mut().insert(s, g);
647 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
648 // you will be kicked off fast isel. See issue #4352 for an example of this.
649 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
651 let len = s.get().len();
652 let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s, false),
653 Type::i8p(cx).to_ref());
654 C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
658 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
660 let len = data.len();
661 let lldata = C_bytes(cx, data);
663 let gsym = token::gensym("binary");
664 let g = format!("binary{}", gsym.uint()).with_c_str(|buf| {
665 llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), buf)
667 llvm::LLVMSetInitializer(g, lldata);
668 llvm::LLVMSetGlobalConstant(g, True);
669 llvm::SetLinkage(g, llvm::InternalLinkage);
671 let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
672 C_struct(cx, &[cs, C_uint(cx, len)], false)
676 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
677 C_struct_in_context(cx.llcx(), elts, packed)
680 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
682 llvm::LLVMConstStructInContext(llcx,
683 elts.as_ptr(), elts.len() as c_uint,
688 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
690 llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
694 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
696 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
700 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
701 C_bytes_in_context(cx.llcx(), bytes)
704 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
706 let ptr = bytes.as_ptr() as *const c_char;
707 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
711 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
714 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
716 debug!("const_get_elt(v={}, us={}, r={})",
717 cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
723 pub fn is_const(v: ValueRef) -> bool {
725 llvm::LLVMIsConstant(v) == True
729 pub fn const_to_int(v: ValueRef) -> i64 {
731 llvm::LLVMConstIntGetSExtValue(v)
735 pub fn const_to_uint(v: ValueRef) -> u64 {
737 llvm::LLVMConstIntGetZExtValue(v)
741 pub fn is_undef(val: ValueRef) -> bool {
743 llvm::LLVMIsUndef(val) != False
747 pub fn is_null(val: ValueRef) -> bool {
749 llvm::LLVMIsNull(val) != False
753 pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
754 t.subst(bcx.tcx(), bcx.fcx.param_substs)
757 pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> {
759 let t = ty::node_id_to_type(tcx, id);
760 monomorphize_type(bcx, t)
763 pub fn expr_ty<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
764 node_id_type(bcx, ex.id)
767 pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> {
768 monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
771 pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
773 trait_ref: Rc<ty::TraitRef<'tcx>>)
774 -> traits::Vtable<'tcx, ()>
777 * Attempts to resolve an obligation. The result is a shallow
778 * vtable resolution -- meaning that we do not (necessarily) resolve
779 * all nested obligations on the impl. Note that type check should
780 * guarantee to us that all nested obligations *could be* resolved
786 // Remove any references to regions; this helps improve caching.
787 let trait_ref = ty_fold::erase_regions(tcx, trait_ref);
789 // First check the cache.
790 match ccx.trait_cache().borrow().get(&trait_ref) {
792 info!("Cache hit: {}", trait_ref.repr(ccx.tcx()));
793 return (*vtable).clone();
798 debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx()));
800 ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id);
801 let infcx = infer::new_infer_ctxt(tcx);
803 // Parameter environment is used to give details about type parameters,
804 // but since we are in trans, everything is fully monomorphized.
805 let param_env = ty::empty_parameter_environment();
807 // Do the initial selection for the obligation. This yields the
808 // shallow result we are looking for -- that is, what specific impl.
809 let mut selcx = traits::SelectionContext::new(&infcx, ¶m_env, tcx);
810 let obligation = traits::Obligation::misc(span, trait_ref.clone());
811 let selection = match selcx.select(&obligation) {
812 Ok(Some(selection)) => selection,
814 // Ambiguity can happen when monomorphizing during trans
815 // expands to some humongo type that never occurred
816 // statically -- this humongo type can then overflow,
817 // leading to an ambiguous result. So report this as an
818 // overflow bug, since I believe this is the only case
819 // where ambiguity can result.
820 debug!("Encountered ambiguity selecting `{}` during trans, \
821 presuming due to overflow",
822 trait_ref.repr(tcx));
823 ccx.sess().span_fatal(
825 "reached the recursion limit during monomorphization");
830 format!("Encountered error `{}` selecting `{}` during trans",
832 trait_ref.repr(tcx)).as_slice())
836 // Currently, we use a fulfillment context to completely resolve
837 // all nested obligations. This is because they can inform the
838 // inference of the impl's type parameters. However, in principle,
839 // we only need to do this until the impl's type parameters are
840 // fully bound. It could be a slight optimization to stop
842 let mut fulfill_cx = traits::FulfillmentContext::new();
843 let vtable = selection.map_move_nested(|obligation| {
844 fulfill_cx.register_obligation(tcx, obligation);
846 match fulfill_cx.select_all_or_error(&infcx, ¶m_env, tcx) {
849 if errors.iter().all(|e| e.is_overflow()) {
850 // See Ok(None) case above.
851 ccx.sess().span_fatal(
853 "reached the recursion limit during monomorphization");
857 format!("Encountered errors `{}` fulfilling `{}` during trans",
859 trait_ref.repr(tcx)).as_slice());
864 // Use skolemize to simultaneously replace all type variables with
865 // their bindings and replace all regions with 'static. This is
866 // sort of overkill because we do not expect there to be any
867 // unbound type variables, hence no skolemized types should ever
869 let vtable = vtable.fold_with(&mut infcx.skolemizer());
871 info!("Cache miss: {}", trait_ref.repr(ccx.tcx()));
872 ccx.trait_cache().borrow_mut().insert(trait_ref,
878 // Key used to lookup values supplied for type parameters in an expr.
879 #[deriving(PartialEq, Show)]
880 pub enum ExprOrMethodCall {
881 // Type parameters for a path like `None::<int>`
884 // Type parameters for a method call like `a.foo::<int>()`
885 MethodCall(typeck::MethodCall)
888 pub fn node_id_substs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
889 node: ExprOrMethodCall)
890 -> subst::Substs<'tcx>
894 let substs = match node {
896 ty::node_id_item_substs(tcx, id).substs
898 MethodCall(method_call) => {
899 (*tcx.method_map.borrow())[method_call].substs.clone()
903 if substs.types.any(|t| ty::type_needs_infer(*t)) {
905 format!("type parameters for node {} include inference types: \
908 substs.repr(bcx.tcx())).as_slice());
911 let substs = substs.erase_regions();
912 substs.subst(tcx, bcx.fcx.param_substs)
915 pub fn langcall(bcx: Block,
920 match bcx.tcx().lang_items.require(li) {
923 let msg = format!("{} {}", msg, s);
925 Some(span) => bcx.tcx().sess.span_fatal(span, msg.as_slice()),
926 None => bcx.tcx().sess.fatal(msg.as_slice()),