]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/common.rs
move Instance to rustc and use it in the collector
[rust.git] / src / librustc_trans / common.rs
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.
4 //
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.
10
11 #![allow(non_camel_case_types, non_snake_case)]
12
13 //! Code that is useful in various trans modules.
14
15 use llvm;
16 use llvm::{ValueRef, ContextRef, TypeKind};
17 use llvm::{True, False, Bool, OperandBundleDef};
18 use rustc::hir::def_id::DefId;
19 use rustc::hir::map::DefPathData;
20 use rustc::util::common::MemoizationMap;
21 use middle::lang_items::LangItem;
22 use base;
23 use builder::Builder;
24 use consts;
25 use declare;
26 use machine;
27 use monomorphize;
28 use type_::Type;
29 use value::Value;
30 use rustc::ty::{self, Ty, TyCtxt};
31 use rustc::ty::layout::Layout;
32 use rustc::ty::subst::{Subst, Substs};
33 use rustc::traits::{self, SelectionContext, Reveal};
34 use rustc::hir;
35
36 use libc::{c_uint, c_char};
37 use std::iter;
38
39 use syntax::ast;
40 use syntax::attr;
41 use syntax::symbol::InternedString;
42 use syntax_pos::Span;
43
44 pub use context::{CrateContext, SharedCrateContext};
45
46 pub fn type_is_fat_ptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
47     if let Layout::FatPointer { .. } = *ccx.layout_of(ty) {
48         true
49     } else {
50         false
51     }
52 }
53
54 pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
55     let layout = ccx.layout_of(ty);
56     match *layout {
57         Layout::CEnum { .. } |
58         Layout::Scalar { .. } |
59         Layout::Vector { .. } => true,
60
61         Layout::FatPointer { .. } => false,
62
63         Layout::Array { .. } |
64         Layout::Univariant { .. } |
65         Layout::General { .. } |
66         Layout::UntaggedUnion { .. } |
67         Layout::RawNullablePointer { .. } |
68         Layout::StructWrappedNullablePointer { .. } => {
69             !layout.is_unsized() && layout.size(&ccx.tcx().data_layout).bytes() == 0
70         }
71     }
72 }
73
74 /// Returns Some([a, b]) if the type has a pair of fields with types a and b.
75 pub fn type_pair_fields<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>)
76                                   -> Option<[Ty<'tcx>; 2]> {
77     match ty.sty {
78         ty::TyAdt(adt, substs) => {
79             assert_eq!(adt.variants.len(), 1);
80             let fields = &adt.variants[0].fields;
81             if fields.len() != 2 {
82                 return None;
83             }
84             Some([monomorphize::field_ty(ccx.tcx(), substs, &fields[0]),
85                   monomorphize::field_ty(ccx.tcx(), substs, &fields[1])])
86         }
87         ty::TyClosure(def_id, substs) => {
88             let mut tys = substs.upvar_tys(def_id, ccx.tcx());
89             tys.next().and_then(|first_ty| tys.next().and_then(|second_ty| {
90                 if tys.next().is_some() {
91                     None
92                 } else {
93                     Some([first_ty, second_ty])
94                 }
95             }))
96         }
97         ty::TyTuple(tys, _) => {
98             if tys.len() != 2 {
99                 return None;
100             }
101             Some([tys[0], tys[1]])
102         }
103         _ => None
104     }
105 }
106
107 /// Returns true if the type is represented as a pair of immediates.
108 pub fn type_is_imm_pair<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>)
109                                   -> bool {
110     match *ccx.layout_of(ty) {
111         Layout::FatPointer { .. } => true,
112         Layout::Univariant { ref variant, .. } => {
113             // There must be only 2 fields.
114             if variant.offsets.len() != 2 {
115                 return false;
116             }
117
118             match type_pair_fields(ccx, ty) {
119                 Some([a, b]) => {
120                     type_is_immediate(ccx, a) && type_is_immediate(ccx, b)
121                 }
122                 None => false
123             }
124         }
125         _ => false
126     }
127 }
128
129 /// Identify types which have size zero at runtime.
130 pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
131     use machine::llsize_of_alloc;
132     use type_of::sizing_type_of;
133     let llty = sizing_type_of(ccx, ty);
134     llsize_of_alloc(ccx, llty) == 0
135 }
136
137 /*
138 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
139 *
140 * An "extern" is an LLVM symbol we wind up emitting an undefined external
141 * reference to. This means "we don't have the thing in this compilation unit,
142 * please make sure you link it in at runtime". This could be a reference to
143 * C code found in a C library, or rust code found in a rust crate.
144 *
145 * Most "externs" are implicitly declared (automatically) as a result of a
146 * user declaring an extern _module_ dependency; this causes the rust driver
147 * to locate an extern crate, scan its compilation metadata, and emit extern
148 * declarations for any symbols used by the declaring crate.
149 *
150 * A "foreign" is an extern that references C (or other non-rust ABI) code.
151 * There is no metadata to scan for extern references so in these cases either
152 * a header-digester like bindgen, or manual function prototypes, have to
153 * serve as declarators. So these are usually given explicitly as prototype
154 * declarations, in rust code, with ABI attributes on them noting which ABI to
155 * link via.
156 *
157 * An "upcall" is a foreign call generated by the compiler (not corresponding
158 * to any user-written call in the code) into the runtime library, to perform
159 * some helper task such as bringing a task to life, allocating memory, etc.
160 *
161 */
162
163 /// A structure representing an active landing pad for the duration of a basic
164 /// block.
165 ///
166 /// Each `Block` may contain an instance of this, indicating whether the block
167 /// is part of a landing pad or not. This is used to make decision about whether
168 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
169 /// use `invoke`) and also about various function call metadata.
170 ///
171 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
172 /// just a bunch of `None` instances (not too interesting), but for MSVC
173 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
174 /// When inside of a landing pad, each function call in LLVM IR needs to be
175 /// annotated with which landing pad it's a part of. This is accomplished via
176 /// the `OperandBundleDef` value created for MSVC landing pads.
177 pub struct Funclet {
178     cleanuppad: ValueRef,
179     operand: OperandBundleDef,
180 }
181
182 impl Funclet {
183     pub fn new(cleanuppad: ValueRef) -> Funclet {
184         Funclet {
185             cleanuppad: cleanuppad,
186             operand: OperandBundleDef::new("funclet", &[cleanuppad]),
187         }
188     }
189
190     pub fn cleanuppad(&self) -> ValueRef {
191         self.cleanuppad
192     }
193
194     pub fn bundle(&self) -> &OperandBundleDef {
195         &self.operand
196     }
197 }
198
199 impl Clone for Funclet {
200     fn clone(&self) -> Funclet {
201         Funclet {
202             cleanuppad: self.cleanuppad,
203             operand: OperandBundleDef::new("funclet", &[self.cleanuppad]),
204         }
205     }
206 }
207
208 pub fn val_ty(v: ValueRef) -> Type {
209     unsafe {
210         Type::from_ref(llvm::LLVMTypeOf(v))
211     }
212 }
213
214 // LLVM constant constructors.
215 pub fn C_null(t: Type) -> ValueRef {
216     unsafe {
217         llvm::LLVMConstNull(t.to_ref())
218     }
219 }
220
221 pub fn C_undef(t: Type) -> ValueRef {
222     unsafe {
223         llvm::LLVMGetUndef(t.to_ref())
224     }
225 }
226
227 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
228     unsafe {
229         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
230     }
231 }
232
233 pub fn C_big_integral(t: Type, u: u128) -> ValueRef {
234     unsafe {
235         let words = [u as u64, u.wrapping_shr(64) as u64];
236         llvm::LLVMConstIntOfArbitraryPrecision(t.to_ref(), 2, words.as_ptr())
237     }
238 }
239
240 pub fn C_floating_f64(f: f64, t: Type) -> ValueRef {
241     unsafe {
242         llvm::LLVMConstReal(t.to_ref(), f)
243     }
244 }
245
246 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
247     C_struct(ccx, &[], false)
248 }
249
250 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
251     C_integral(Type::i1(ccx), val as u64, false)
252 }
253
254 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
255     C_integral(Type::i32(ccx), i as u64, true)
256 }
257
258 pub fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef {
259     C_integral(Type::i32(ccx), i as u64, false)
260 }
261
262 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
263     C_integral(Type::i64(ccx), i, false)
264 }
265
266 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
267     let v = i.as_u64();
268
269     let bit_size = machine::llbitsize_of_real(ccx, ccx.int_type());
270
271     if bit_size < 64 {
272         // make sure it doesn't overflow
273         assert!(v < (1<<bit_size));
274     }
275
276     C_integral(ccx.int_type(), v, false)
277 }
278
279 pub trait AsI64 { fn as_i64(self) -> i64; }
280 pub trait AsU64 { fn as_u64(self) -> u64; }
281
282 // FIXME: remove the intptr conversions, because they
283 // are host-architecture-dependent
284 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
285 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
286 impl AsI64 for isize { fn as_i64(self) -> i64 { self as i64 }}
287
288 impl AsU64 for u64  { fn as_u64(self) -> u64 { self as u64 }}
289 impl AsU64 for u32  { fn as_u64(self) -> u64 { self as u64 }}
290 impl AsU64 for usize { fn as_u64(self) -> u64 { self as u64 }}
291
292 pub fn C_u8(ccx: &CrateContext, i: u8) -> ValueRef {
293     C_integral(Type::i8(ccx), i as u64, false)
294 }
295
296
297 // This is a 'c-like' raw string, which differs from
298 // our boxed-and-length-annotated strings.
299 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
300     unsafe {
301         if let Some(&llval) = cx.const_cstr_cache().borrow().get(&s) {
302             return llval;
303         }
304
305         let sc = llvm::LLVMConstStringInContext(cx.llcx(),
306                                                 s.as_ptr() as *const c_char,
307                                                 s.len() as c_uint,
308                                                 !null_terminated as Bool);
309         let sym = cx.generate_local_symbol_name("str");
310         let g = declare::define_global(cx, &sym[..], val_ty(sc)).unwrap_or_else(||{
311             bug!("symbol `{}` is already defined", sym);
312         });
313         llvm::LLVMSetInitializer(g, sc);
314         llvm::LLVMSetGlobalConstant(g, True);
315         llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
316
317         cx.const_cstr_cache().borrow_mut().insert(s, g);
318         g
319     }
320 }
321
322 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
323 // you will be kicked off fast isel. See issue #4352 for an example of this.
324 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
325     let len = s.len();
326     let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
327     C_named_struct(cx.str_slice_type(), &[cs, C_uint(cx, len)])
328 }
329
330 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
331     C_struct_in_context(cx.llcx(), elts, packed)
332 }
333
334 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
335     unsafe {
336         llvm::LLVMConstStructInContext(llcx,
337                                        elts.as_ptr(), elts.len() as c_uint,
338                                        packed as Bool)
339     }
340 }
341
342 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
343     unsafe {
344         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
345     }
346 }
347
348 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
349     unsafe {
350         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
351     }
352 }
353
354 pub fn C_vector(elts: &[ValueRef]) -> ValueRef {
355     unsafe {
356         return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
357     }
358 }
359
360 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
361     C_bytes_in_context(cx.llcx(), bytes)
362 }
363
364 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
365     unsafe {
366         let ptr = bytes.as_ptr() as *const c_char;
367         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
368     }
369 }
370
371 pub fn const_get_elt(v: ValueRef, us: &[c_uint])
372               -> ValueRef {
373     unsafe {
374         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
375
376         debug!("const_get_elt(v={:?}, us={:?}, r={:?})",
377                Value(v), us, Value(r));
378
379         r
380     }
381 }
382
383 pub fn const_to_uint(v: ValueRef) -> u64 {
384     unsafe {
385         llvm::LLVMConstIntGetZExtValue(v)
386     }
387 }
388
389 fn is_const_integral(v: ValueRef) -> bool {
390     unsafe {
391         !llvm::LLVMIsAConstantInt(v).is_null()
392     }
393 }
394
395 #[inline]
396 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
397     ((hi as u128) << 64) | (lo as u128)
398 }
399
400 pub fn const_to_opt_u128(v: ValueRef, sign_ext: bool) -> Option<u128> {
401     unsafe {
402         if is_const_integral(v) {
403             let (mut lo, mut hi) = (0u64, 0u64);
404             let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
405                                                        &mut hi as *mut u64, &mut lo as *mut u64);
406             if success {
407                 Some(hi_lo_to_u128(lo, hi))
408             } else {
409                 None
410             }
411         } else {
412             None
413         }
414     }
415 }
416
417 pub fn is_undef(val: ValueRef) -> bool {
418     unsafe {
419         llvm::LLVMIsUndef(val) != False
420     }
421 }
422
423 #[allow(dead_code)] // potentially useful
424 pub fn is_null(val: ValueRef) -> bool {
425     unsafe {
426         llvm::LLVMIsNull(val) != False
427     }
428 }
429
430 /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we
431 /// do not (necessarily) resolve all nested obligations on the impl. Note that type check should
432 /// guarantee to us that all nested obligations *could be* resolved if we wanted to.
433 pub fn fulfill_obligation<'a, 'tcx>(scx: &SharedCrateContext<'a, 'tcx>,
434                                     span: Span,
435                                     trait_ref: ty::PolyTraitRef<'tcx>)
436                                     -> traits::Vtable<'tcx, ()>
437 {
438     let tcx = scx.tcx();
439
440     // Remove any references to regions; this helps improve caching.
441     let trait_ref = tcx.erase_regions(&trait_ref);
442
443     scx.trait_cache().memoize(trait_ref, || {
444         debug!("trans::fulfill_obligation(trait_ref={:?}, def_id={:?})",
445                trait_ref, trait_ref.def_id());
446
447         // Do the initial selection for the obligation. This yields the
448         // shallow result we are looking for -- that is, what specific impl.
449         tcx.infer_ctxt((), Reveal::All).enter(|infcx| {
450             let mut selcx = SelectionContext::new(&infcx);
451
452             let obligation_cause = traits::ObligationCause::misc(span,
453                                                              ast::DUMMY_NODE_ID);
454             let obligation = traits::Obligation::new(obligation_cause,
455                                                      trait_ref.to_poly_trait_predicate());
456
457             let selection = match selcx.select(&obligation) {
458                 Ok(Some(selection)) => selection,
459                 Ok(None) => {
460                     // Ambiguity can happen when monomorphizing during trans
461                     // expands to some humongo type that never occurred
462                     // statically -- this humongo type can then overflow,
463                     // leading to an ambiguous result. So report this as an
464                     // overflow bug, since I believe this is the only case
465                     // where ambiguity can result.
466                     debug!("Encountered ambiguity selecting `{:?}` during trans, \
467                             presuming due to overflow",
468                            trait_ref);
469                     tcx.sess.span_fatal(span,
470                         "reached the recursion limit during monomorphization \
471                          (selection ambiguity)");
472                 }
473                 Err(e) => {
474                     span_bug!(span, "Encountered error `{:?}` selecting `{:?}` during trans",
475                               e, trait_ref)
476                 }
477             };
478
479             debug!("fulfill_obligation: selection={:?}", selection);
480
481             // Currently, we use a fulfillment context to completely resolve
482             // all nested obligations. This is because they can inform the
483             // inference of the impl's type parameters.
484             let mut fulfill_cx = traits::FulfillmentContext::new();
485             let vtable = selection.map(|predicate| {
486                 debug!("fulfill_obligation: register_predicate_obligation {:?}", predicate);
487                 fulfill_cx.register_predicate_obligation(&infcx, predicate);
488             });
489             let vtable = infcx.drain_fulfillment_cx_or_panic(span, &mut fulfill_cx, &vtable);
490
491             info!("Cache miss: {:?} => {:?}", trait_ref, vtable);
492             vtable
493         })
494     })
495 }
496
497 pub fn langcall(tcx: TyCtxt,
498                 span: Option<Span>,
499                 msg: &str,
500                 li: LangItem)
501                 -> DefId {
502     match tcx.lang_items.require(li) {
503         Ok(id) => id,
504         Err(s) => {
505             let msg = format!("{} {}", msg, s);
506             match span {
507                 Some(span) => tcx.sess.span_fatal(span, &msg[..]),
508                 None => tcx.sess.fatal(&msg[..]),
509             }
510         }
511     }
512 }
513
514 // To avoid UB from LLVM, these two functions mask RHS with an
515 // appropriate mask unconditionally (i.e. the fallback behavior for
516 // all shifts). For 32- and 64-bit types, this matches the semantics
517 // of Java. (See related discussion on #1877 and #10183.)
518
519 pub fn build_unchecked_lshift<'a, 'tcx>(
520     bcx: &Builder<'a, 'tcx>,
521     lhs: ValueRef,
522     rhs: ValueRef
523 ) -> ValueRef {
524     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
525     // #1877, #10183: Ensure that input is always valid
526     let rhs = shift_mask_rhs(bcx, rhs);
527     bcx.shl(lhs, rhs)
528 }
529
530 pub fn build_unchecked_rshift<'a, 'tcx>(
531     bcx: &Builder<'a, 'tcx>, lhs_t: Ty<'tcx>, lhs: ValueRef, rhs: ValueRef
532 ) -> ValueRef {
533     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
534     // #1877, #10183: Ensure that input is always valid
535     let rhs = shift_mask_rhs(bcx, rhs);
536     let is_signed = lhs_t.is_signed();
537     if is_signed {
538         bcx.ashr(lhs, rhs)
539     } else {
540         bcx.lshr(lhs, rhs)
541     }
542 }
543
544 fn shift_mask_rhs<'a, 'tcx>(bcx: &Builder<'a, 'tcx>, rhs: ValueRef) -> ValueRef {
545     let rhs_llty = val_ty(rhs);
546     bcx.and(rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false))
547 }
548
549 pub fn shift_mask_val<'a, 'tcx>(
550     bcx: &Builder<'a, 'tcx>,
551     llty: Type,
552     mask_llty: Type,
553     invert: bool
554 ) -> ValueRef {
555     let kind = llty.kind();
556     match kind {
557         TypeKind::Integer => {
558             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
559             let val = llty.int_width() - 1;
560             if invert {
561                 C_integral(mask_llty, !val, true)
562             } else {
563                 C_integral(mask_llty, val, false)
564             }
565         },
566         TypeKind::Vector => {
567             let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
568             bcx.vector_splat(mask_llty.vector_length(), mask)
569         },
570         _ => bug!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
571     }
572 }
573
574 pub fn ty_fn_sig<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
575                            ty: Ty<'tcx>)
576                            -> ty::PolyFnSig<'tcx>
577 {
578     match ty.sty {
579         ty::TyFnDef(_, _, sig) => sig,
580         // Shims currently have type TyFnPtr. Not sure this should remain.
581         ty::TyFnPtr(sig) => sig,
582         ty::TyClosure(def_id, substs) => {
583             let tcx = ccx.tcx();
584             let sig = tcx.closure_type(def_id).subst(tcx, substs.substs);
585
586             let env_region = ty::ReLateBound(ty::DebruijnIndex::new(1), ty::BrEnv);
587             let env_ty = match tcx.closure_kind(def_id) {
588                 ty::ClosureKind::Fn => tcx.mk_imm_ref(tcx.mk_region(env_region), ty),
589                 ty::ClosureKind::FnMut => tcx.mk_mut_ref(tcx.mk_region(env_region), ty),
590                 ty::ClosureKind::FnOnce => ty,
591             };
592
593             sig.map_bound(|sig| tcx.mk_fn_sig(
594                 iter::once(env_ty).chain(sig.inputs().iter().cloned()),
595                 sig.output(),
596                 sig.variadic,
597                 sig.unsafety,
598                 sig.abi
599             ))
600         }
601         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
602     }
603 }
604
605 pub fn requests_inline<'a, 'tcx>(
606     tcx: TyCtxt<'a, 'tcx, 'tcx>,
607     instance: &ty::Instance<'tcx>
608 ) -> bool {
609     let def_id = match instance.def {
610         ty::InstanceDef::Item(def_id) => def_id,
611         _ => return true
612     };
613     match tcx.def_key(def_id).disambiguated_data.data {
614         DefPathData::StructCtor |
615         DefPathData::EnumVariant(..) |
616         DefPathData::ClosureExpr => true,
617         _ => attr::requests_inline(&tcx.get_attrs(def_id)[..]),
618     }
619 }
620 /// Given a DefId and some Substs, produces the monomorphic item type.
621 pub fn def_ty<'a, 'tcx>(shared: &SharedCrateContext<'a, 'tcx>,
622                         def_id: DefId,
623                         substs: &'tcx Substs<'tcx>)
624                         -> Ty<'tcx>
625 {
626     let ty = shared.tcx().item_type(def_id);
627     monomorphize::apply_param_substs(shared, substs, &ty)
628 }
629
630 /// Return the substituted type of an instance.
631 pub fn instance_ty<'a, 'tcx>(shared: &SharedCrateContext<'a, 'tcx>,
632                              instance: &ty::Instance<'tcx>)
633                              -> Ty<'tcx>
634 {
635     let ty = instance.def.def_ty(shared.tcx());
636     monomorphize::apply_param_substs(shared, instance.substs, &ty)
637 }
638
639 pub fn find_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
640                              name: ast::Name,
641                              substs: &'tcx Substs<'tcx>,
642                              impl_data: &traits::VtableImplData<'tcx, ()>)
643                              -> ty::Instance<'tcx>
644 {
645     let (def_id, substs) = traits::find_method(tcx, name, substs, impl_data);
646     let substs = tcx.erase_regions(&substs);
647     ty::Instance::new(def_id, substs)
648 }