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 use driver::session::Session;
17 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ContextRef};
18 use llvm::{True, False, Bool};
20 use middle::lang_items::LangItem;
21 use middle::mem_categorization as mc;
23 use middle::subst::Subst;
24 use middle::trans::base;
25 use middle::trans::build;
26 use middle::trans::cleanup;
27 use middle::trans::datum;
28 use middle::trans::debuginfo;
29 use middle::trans::type_::Type;
30 use middle::trans::type_of;
34 use middle::ty_fold::TypeFoldable;
36 use middle::typeck::infer;
37 use util::ppaux::Repr;
38 use util::nodemap::{DefIdMap, NodeMap};
40 use arena::TypedArena;
41 use std::collections::HashMap;
42 use libc::{c_uint, c_longlong, c_ulonglong, c_char};
43 use std::c_str::ToCStr;
44 use std::cell::{Cell, RefCell};
47 use syntax::ast::Ident;
49 use syntax::ast_map::{PathElem, PathName};
50 use syntax::codemap::Span;
51 use syntax::parse::token::InternedString;
52 use syntax::parse::token;
54 pub use middle::trans::context::CrateContext;
56 fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
57 match ty::get(ty).sty {
58 ty::ty_struct(def_id, ref substs) => {
59 let fields = ty::struct_fields(ccx.tcx(), def_id, substs);
61 fields.get(0).ident.name ==
62 token::special_idents::unnamed_field.name &&
63 type_is_immediate(ccx, fields.get(0).mt.ty)
69 pub fn type_is_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
70 use middle::trans::machine::llsize_of_alloc;
71 use middle::trans::type_of::sizing_type_of;
74 let simple = ty::type_is_scalar(ty) ||
75 ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
76 type_is_newtype_immediate(ccx, ty) || ty::type_is_bot(ty) ||
77 ty::type_is_simd(tcx, ty);
78 if simple && !ty::type_is_fat_ptr(tcx, ty) {
81 if !ty::type_is_sized(tcx, ty) {
84 match ty::get(ty).sty {
86 ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) |
87 ty::ty_unboxed_closure(..) => {
88 let llty = sizing_type_of(ccx, ty);
89 llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type())
91 _ => type_is_zero_size(ccx, ty)
95 pub fn type_is_zero_size(ccx: &CrateContext, ty: ty::t) -> bool {
97 * Identify types which have size zero at runtime.
100 use middle::trans::machine::llsize_of_alloc;
101 use middle::trans::type_of::sizing_type_of;
102 let llty = sizing_type_of(ccx, ty);
103 llsize_of_alloc(ccx, llty) == 0
106 pub fn return_type_is_void(ccx: &CrateContext, ty: ty::t) -> bool {
108 * Identifies types which we declare to be equivalent to `void`
109 * in C for the purpose of function return types. These are
110 * `()`, bot, and uninhabited enums. Note that all such types
111 * are also zero-size, but not all zero-size types use a `void`
112 * return type (in order to aid with C ABI compatibility).
115 ty::type_is_nil(ty) || ty::type_is_bot(ty) || ty::type_is_empty(ccx.tcx(), ty)
118 /// Generates a unique symbol based off the name given. This is used to create
119 /// unique symbols for things like closures.
120 pub fn gensym_name(name: &str) -> PathElem {
121 let num = token::gensym(name).uint();
122 // use one colon which will get translated to a period by the mangler, and
123 // we're guaranteed that `num` is globally unique for this crate.
124 PathName(token::gensym(format!("{}:{}", name, num).as_slice()))
127 pub struct tydesc_info {
129 pub tydesc: ValueRef,
136 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
138 * An "extern" is an LLVM symbol we wind up emitting an undefined external
139 * reference to. This means "we don't have the thing in this compilation unit,
140 * please make sure you link it in at runtime". This could be a reference to
141 * C code found in a C library, or rust code found in a rust crate.
143 * Most "externs" are implicitly declared (automatically) as a result of a
144 * user declaring an extern _module_ dependency; this causes the rust driver
145 * to locate an extern crate, scan its compilation metadata, and emit extern
146 * declarations for any symbols used by the declaring crate.
148 * A "foreign" is an extern that references C (or other non-rust ABI) code.
149 * There is no metadata to scan for extern references so in these cases either
150 * a header-digester like bindgen, or manual function prototypes, have to
151 * serve as declarators. So these are usually given explicitly as prototype
152 * declarations, in rust code, with ABI attributes on them noting which ABI to
155 * An "upcall" is a foreign call generated by the compiler (not corresponding
156 * to any user-written call in the code) into the runtime library, to perform
157 * some helper task such as bringing a task to life, allocating memory, etc.
161 pub struct NodeInfo {
166 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
167 NodeInfo { id: expr.id, span: expr.span }
170 pub struct BuilderRef_res {
174 impl Drop for BuilderRef_res {
177 llvm::LLVMDisposeBuilder(self.b);
182 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
188 pub type ExternMap = HashMap<String, ValueRef>;
190 // Here `self_ty` is the real type of the self parameter to this method. It
191 // will only be set in the case of default methods.
192 pub struct param_substs {
193 pub substs: subst::Substs,
197 pub fn empty() -> param_substs {
199 substs: subst::Substs::trans_empty(),
203 pub fn validate(&self) {
204 assert!(self.substs.types.all(|t| !ty::type_needs_infer(*t)));
208 impl Repr for param_substs {
209 fn repr(&self, tcx: &ty::ctxt) -> String {
210 self.substs.repr(tcx)
215 fn substp(&self, tcx: &ty::ctxt, param_substs: ¶m_substs)
219 impl<T:Subst+Clone> SubstP for T {
220 fn substp(&self, tcx: &ty::ctxt, substs: ¶m_substs) -> T {
221 self.subst(tcx, &substs.substs)
225 // work around bizarre resolve errors
226 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
227 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
229 // Function context. Every LLVM function we create will have one of
231 pub struct FunctionContext<'a, 'tcx: 'a> {
232 // The ValueRef returned from a call to llvm::LLVMAddFunction; the
233 // address of the first instruction in the sequence of
234 // instructions for this function that will go in the .text
235 // section of the executable we're generating.
238 // The environment argument in a closure.
239 pub llenv: Option<ValueRef>,
241 // A pointer to where to store the return value. If the return type is
242 // immediate, this points to an alloca in the function. Otherwise, it's a
243 // pointer to the hidden first parameter of the function. After function
244 // construction, this should always be Some.
245 pub llretslotptr: Cell<Option<ValueRef>>,
247 // These pub elements: "hoisted basic blocks" containing
248 // administrative activities that have to happen in only one place in
249 // the function, due to LLVM's quirks.
250 // A marker for the place where we want to insert the function's static
251 // allocas, so that LLVM will coalesce them into a single alloca call.
252 pub alloca_insert_pt: Cell<Option<ValueRef>>,
253 pub llreturn: Cell<Option<BasicBlockRef>>,
255 // If the function has any nested return's, including something like:
256 // fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then
257 // we use a separate alloca for each return
258 pub needs_ret_allocas: bool,
260 // The a value alloca'd for calls to upcalls.rust_personality. Used when
261 // outputting the resume instruction.
262 pub personality: Cell<Option<ValueRef>>,
264 // True if the caller expects this fn to use the out pointer to
265 // return. Either way, your code should write into the slot llretslotptr
266 // points to, but if this value is false, that slot will be a local alloca.
267 pub caller_expects_out_pointer: bool,
269 // Maps the DefId's for local variables to the allocas created for
270 // them in llallocas.
271 pub lllocals: RefCell<NodeMap<LvalueDatum>>,
273 // Same as above, but for closure upvars
274 pub llupvars: RefCell<NodeMap<ValueRef>>,
276 // The NodeId of the function, or -1 if it doesn't correspond to
277 // a user-defined function.
280 // If this function is being monomorphized, this contains the type
281 // substitutions used.
282 pub param_substs: &'a param_substs,
284 // The source span and nesting context where this function comes from, for
285 // error reporting and symbol generation.
286 pub span: Option<Span>,
288 // The arena that blocks are allocated from.
289 pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>,
291 // This function's enclosing crate context.
292 pub ccx: &'a CrateContext<'a, 'tcx>,
294 // Used and maintained by the debuginfo module.
295 pub debug_context: debuginfo::FunctionDebugContext,
298 pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>,
301 impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
302 pub fn arg_pos(&self, arg: uint) -> uint {
303 let arg = self.env_arg_pos() + arg;
304 if self.llenv.is_some() {
311 pub fn out_arg_pos(&self) -> uint {
312 assert!(self.caller_expects_out_pointer);
316 pub fn env_arg_pos(&self) -> uint {
317 if self.caller_expects_out_pointer {
324 pub fn cleanup(&self) {
326 llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
332 pub fn get_llreturn(&self) -> BasicBlockRef {
333 if self.llreturn.get().is_none() {
335 self.llreturn.set(Some(unsafe {
336 "return".with_c_str(|buf| {
337 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn, buf)
342 self.llreturn.get().unwrap()
345 pub fn get_ret_slot(&self, bcx: Block, ty: ty::t, name: &str) -> ValueRef {
346 if self.needs_ret_allocas {
347 base::alloca_no_lifetime(bcx, type_of::type_of(bcx.ccx(), ty), name)
349 self.llretslotptr.get().unwrap()
353 pub fn new_block(&'a self,
356 opt_node_id: Option<ast::NodeId>)
359 let llbb = name.with_c_str(|buf| {
360 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
364 BlockS::new(llbb, is_lpad, opt_node_id, self)
368 pub fn new_id_block(&'a self,
370 node_id: ast::NodeId)
372 self.new_block(false, name, Some(node_id))
375 pub fn new_temp_block(&'a self,
378 self.new_block(false, name, None)
381 pub fn join_blocks(&'a self,
383 in_cxs: &[Block<'a, 'tcx>])
385 let out = self.new_id_block("join", id);
386 let mut reachable = false;
387 for bcx in in_cxs.iter() {
388 if !bcx.unreachable.get() {
389 build::Br(*bcx, out.llbb);
394 build::Unreachable(out);
400 // Basic block context. We create a block context for each basic block
401 // (single-entry, single-exit sequence of instructions) we generate from Rust
402 // code. Each basic block we generate is attached to a function, typically
403 // with many basic blocks per function. All the basic blocks attached to a
404 // function are organized as a directed graph.
405 pub struct BlockS<'blk, 'tcx: 'blk> {
406 // The BasicBlockRef returned from a call to
407 // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
408 // block to the function pointed to by llfn. We insert
409 // instructions into that block by way of this block context.
410 // The block pointing to this one in the function's digraph.
411 pub llbb: BasicBlockRef,
412 pub terminated: Cell<bool>,
413 pub unreachable: Cell<bool>,
415 // Is this block part of a landing pad?
418 // AST node-id associated with this block, if any. Used for
419 // debugging purposes only.
420 pub opt_node_id: Option<ast::NodeId>,
422 // The function context for the function to which this block is
424 pub fcx: &'blk FunctionContext<'blk, 'tcx>,
427 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
429 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
430 pub fn new(llbb: BasicBlockRef,
432 opt_node_id: Option<ast::NodeId>,
433 fcx: &'blk FunctionContext<'blk, 'tcx>)
434 -> Block<'blk, 'tcx> {
435 fcx.block_arena.alloc(BlockS {
437 terminated: Cell::new(false),
438 unreachable: Cell::new(false),
440 opt_node_id: opt_node_id,
445 pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
448 pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
451 pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
453 pub fn ident(&self, ident: Ident) -> String {
454 token::get_ident(ident).get().to_string()
457 pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
458 self.tcx().map.node_to_string(id).to_string()
461 pub fn expr_to_string(&self, e: &ast::Expr) -> String {
465 pub fn def(&self, nid: ast::NodeId) -> def::Def {
466 match self.tcx().def_map.borrow().find(&nid) {
467 Some(v) => v.clone(),
469 self.tcx().sess.bug(format!(
470 "no def associated with node id {}", nid).as_slice());
475 pub fn val_to_string(&self, val: ValueRef) -> String {
476 self.ccx().tn().val_to_string(val)
479 pub fn llty_str(&self, ty: Type) -> String {
480 self.ccx().tn().type_to_string(ty)
483 pub fn ty_to_string(&self, t: ty::t) -> String {
487 pub fn to_str(&self) -> String {
488 format!("[block {:p}]", self)
492 impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> {
493 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
497 fn node_ty(&self, id: ast::NodeId) -> mc::McResult<ty::t> {
498 Ok(node_id_type(self, id))
501 fn node_method_ty(&self, method_call: typeck::MethodCall) -> Option<ty::t> {
502 self.tcx().method_map.borrow().find(&method_call).map(|method| method.ty)
505 fn adjustments<'a>(&'a self) -> &'a RefCell<NodeMap<ty::AutoAdjustment>> {
506 &self.tcx().adjustments
509 fn is_method_call(&self, id: ast::NodeId) -> bool {
510 self.tcx().method_map.borrow().contains_key(&typeck::MethodCall::expr(id))
513 fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option<ast::NodeId> {
514 self.tcx().region_maps.temporary_scope(rvalue_id)
517 fn unboxed_closures<'a>(&'a self)
518 -> &'a RefCell<DefIdMap<ty::UnboxedClosure>> {
519 &self.tcx().unboxed_closures
522 fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow {
523 self.tcx().upvar_borrow_map.borrow().get_copy(&upvar_id)
526 fn capture_mode(&self, closure_expr_id: ast::NodeId)
527 -> ast::CaptureClause {
528 self.tcx().capture_modes.borrow().get_copy(&closure_expr_id)
532 pub struct Result<'blk, 'tcx: 'blk> {
533 pub bcx: Block<'blk, 'tcx>,
537 impl<'b, 'tcx> Result<'b, 'tcx> {
538 pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
546 pub fn val_ty(v: ValueRef) -> Type {
548 Type::from_ref(llvm::LLVMTypeOf(v))
552 // LLVM constant constructors.
553 pub fn C_null(t: Type) -> ValueRef {
555 llvm::LLVMConstNull(t.to_ref())
559 pub fn C_undef(t: Type) -> ValueRef {
561 llvm::LLVMGetUndef(t.to_ref())
565 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
567 llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
571 pub fn C_floating(s: &str, t: Type) -> ValueRef {
573 s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
577 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
578 C_struct(ccx, [], false)
581 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
582 C_integral(Type::i1(ccx), val as u64, false)
585 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
586 C_integral(Type::i32(ccx), i as u64, true)
589 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
590 C_integral(Type::i64(ccx), i as u64, true)
593 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
594 C_integral(Type::i64(ccx), i, false)
597 pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
598 C_integral(ccx.int_type(), i as u64, true)
601 pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
602 C_integral(ccx.int_type(), i as u64, false)
605 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
606 C_integral(Type::i8(ccx), i as u64, false)
610 // This is a 'c-like' raw string, which differs from
611 // our boxed-and-length-annotated strings.
612 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
614 match cx.const_cstr_cache().borrow().find(&s) {
615 Some(&llval) => return llval,
619 let sc = llvm::LLVMConstStringInContext(cx.llcx(),
620 s.get().as_ptr() as *const c_char,
621 s.get().len() as c_uint,
622 !null_terminated as Bool);
624 let gsym = token::gensym("str");
625 let g = format!("str{}", gsym.uint()).with_c_str(|buf| {
626 llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf)
628 llvm::LLVMSetInitializer(g, sc);
629 llvm::LLVMSetGlobalConstant(g, True);
630 llvm::SetLinkage(g, llvm::InternalLinkage);
632 cx.const_cstr_cache().borrow_mut().insert(s, g);
637 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
638 // you will be kicked off fast isel. See issue #4352 for an example of this.
639 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
641 let len = s.get().len();
642 let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s, false),
643 Type::i8p(cx).to_ref());
644 C_named_struct(cx.tn().find_type("str_slice").unwrap(), [cs, C_uint(cx, len)])
648 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
650 let len = data.len();
651 let lldata = C_bytes(cx, data);
653 let gsym = token::gensym("binary");
654 let g = format!("binary{}", gsym.uint()).with_c_str(|buf| {
655 llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), buf)
657 llvm::LLVMSetInitializer(g, lldata);
658 llvm::LLVMSetGlobalConstant(g, True);
659 llvm::SetLinkage(g, llvm::InternalLinkage);
661 let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
662 C_struct(cx, [cs, C_uint(cx, len)], false)
666 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
667 C_struct_in_context(cx.llcx(), elts, packed)
670 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
672 llvm::LLVMConstStructInContext(llcx,
673 elts.as_ptr(), elts.len() as c_uint,
678 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
680 llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
684 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
686 return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
690 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
691 C_bytes_in_context(cx.llcx(), bytes)
694 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
696 let ptr = bytes.as_ptr() as *const c_char;
697 return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
701 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
704 let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
706 debug!("const_get_elt(v={}, us={}, r={})",
707 cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
713 pub fn is_const(v: ValueRef) -> bool {
715 llvm::LLVMIsConstant(v) == True
719 pub fn const_to_int(v: ValueRef) -> c_longlong {
721 llvm::LLVMConstIntGetSExtValue(v)
725 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
727 llvm::LLVMConstIntGetZExtValue(v)
731 pub fn is_undef(val: ValueRef) -> bool {
733 llvm::LLVMIsUndef(val) != False
737 pub fn is_null(val: ValueRef) -> bool {
739 llvm::LLVMIsNull(val) != False
743 pub fn monomorphize_type(bcx: &BlockS, t: ty::t) -> ty::t {
744 t.subst(bcx.tcx(), &bcx.fcx.param_substs.substs)
747 pub fn node_id_type(bcx: &BlockS, id: ast::NodeId) -> ty::t {
749 let t = ty::node_id_to_type(tcx, id);
750 monomorphize_type(bcx, t)
753 pub fn expr_ty(bcx: Block, ex: &ast::Expr) -> ty::t {
754 node_id_type(bcx, ex.id)
757 pub fn expr_ty_adjusted(bcx: Block, ex: &ast::Expr) -> ty::t {
758 monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
761 pub fn fulfill_obligation(ccx: &CrateContext,
763 trait_ref: Rc<ty::TraitRef>)
764 -> traits::Vtable<()>
767 * Attempts to resolve an obligation. The result is a shallow
768 * vtable resolution -- meaning that we do not (necessarily) resolve
769 * all nested obligations on the impl. Note that type check should
770 * guarantee to us that all nested obligations *could be* resolved
776 // Remove any references to regions; this helps improve caching.
777 let trait_ref = ty_fold::erase_regions(tcx, trait_ref);
779 // First check the cache.
780 match ccx.trait_cache().borrow().find(&trait_ref) {
782 info!("Cache hit: {}", trait_ref.repr(ccx.tcx()));
783 return (*vtable).clone();
788 ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id);
789 let infcx = infer::new_infer_ctxt(tcx);
791 // Parameter environment is used to give details about type parameters,
792 // but since we are in trans, everything is fully monomorphized.
793 let param_env = ty::empty_parameter_environment();
795 // Do the initial selection for the obligation. This yields the
796 // shallow result we are looking for -- that is, what specific impl.
797 let mut selcx = traits::SelectionContext::new(&infcx, ¶m_env, tcx);
798 let obligation = traits::Obligation::misc(span, trait_ref.clone());
799 let selection = match selcx.select(&obligation) {
800 Ok(Some(selection)) => selection,
802 // Ambiguity can happen when monomorphizing during trans
803 // expands to some humongo type that never occurred
804 // statically -- this humongo type can then overflow,
805 // leading to an ambiguous result. So report this as an
806 // overflow bug, since I believe this is the only case
807 // where ambiguity can result.
808 debug!("Encountered ambiguity selecting `{}` during trans, \
809 presuming due to overflow",
810 trait_ref.repr(tcx));
811 ccx.sess().span_fatal(
813 "reached the recursion limit during monomorphization");
818 format!("Encountered error `{}` selecting `{}` during trans",
820 trait_ref.repr(tcx)).as_slice())
824 // Currently, we use a fulfillment context to completely resolve
825 // all nested obligations. This is because they can inform the
826 // inference of the impl's type parameters. However, in principle,
827 // we only need to do this until the impl's type parameters are
828 // fully bound. It could be a slight optimization to stop
830 let mut fulfill_cx = traits::FulfillmentContext::new();
831 let vtable = selection.map_move_nested(|obligation| {
832 fulfill_cx.register_obligation(tcx, obligation);
834 match fulfill_cx.select_all_or_error(&infcx, ¶m_env, tcx) {
837 if errors.iter().all(|e| e.is_overflow()) {
838 // See Ok(None) case above.
839 ccx.sess().span_fatal(
841 "reached the recursion limit during monomorphization");
845 format!("Encountered errors `{}` fulfilling `{}` during trans",
847 trait_ref.repr(tcx)).as_slice());
852 // Use skolemize to simultaneously replace all type variables with
853 // their bindings and replace all regions with 'static. This is
854 // sort of overkill because we do not expect there to be any
855 // unbound type variables, hence no skolemized types should ever
857 let vtable = vtable.fold_with(&mut infcx.skolemizer());
859 info!("Cache miss: {}", trait_ref.repr(ccx.tcx()));
860 ccx.trait_cache().borrow_mut().insert(trait_ref,
866 // Key used to lookup values supplied for type parameters in an expr.
867 #[deriving(PartialEq, Show)]
868 pub enum ExprOrMethodCall {
869 // Type parameters for a path like `None::<int>`
872 // Type parameters for a method call like `a.foo::<int>()`
873 MethodCall(typeck::MethodCall)
876 pub fn node_id_substs(bcx: Block,
877 node: ExprOrMethodCall)
882 let substs = match node {
884 ty::node_id_item_substs(tcx, id).substs
886 MethodCall(method_call) => {
887 tcx.method_map.borrow().get(&method_call).substs.clone()
891 if substs.types.any(|t| ty::type_needs_infer(*t)) {
893 format!("type parameters for node {} include inference types: \
896 substs.repr(bcx.tcx())).as_slice());
899 let substs = substs.erase_regions();
900 substs.substp(tcx, bcx.fcx.param_substs)
903 pub fn langcall(bcx: Block,
908 match bcx.tcx().lang_items.require(li) {
911 let msg = format!("{} {}", msg, s);
913 Some(span) => bcx.tcx().sess.span_fatal(span, msg.as_slice()),
914 None => bcx.tcx().sess.fatal(msg.as_slice()),