]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/common.rs
auto merge of #15371 : pnkfelix/rust/fsk-render-dataflow-on-dot, r=alexcrichton
[rust.git] / src / librustc / middle / 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_functions)]
12
13 //! Code that is useful in various trans modules.
14
15 use driver::session::Session;
16 use llvm;
17 use llvm::{ValueRef, BasicBlockRef, BuilderRef};
18 use llvm::{True, False, Bool};
19 use middle::def;
20 use middle::lang_items::LangItem;
21 use middle::subst;
22 use middle::subst::Subst;
23 use middle::trans::build;
24 use middle::trans::cleanup;
25 use middle::trans::datum;
26 use middle::trans::debuginfo;
27 use middle::trans::type_::Type;
28 use middle::ty;
29 use middle::typeck;
30 use util::ppaux::Repr;
31 use util::nodemap::NodeMap;
32
33 use arena::TypedArena;
34 use std::collections::HashMap;
35 use libc::{c_uint, c_longlong, c_ulonglong, c_char};
36 use std::c_str::ToCStr;
37 use std::cell::{Cell, RefCell};
38 use std::vec::Vec;
39 use syntax::ast::Ident;
40 use syntax::ast;
41 use syntax::ast_map::{PathElem, PathName};
42 use syntax::codemap::Span;
43 use syntax::parse::token::InternedString;
44 use syntax::parse::token;
45
46 pub use middle::trans::context::CrateContext;
47
48 fn type_is_newtype_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
49     match ty::get(ty).sty {
50         ty::ty_struct(def_id, ref substs) => {
51             let fields = ty::struct_fields(ccx.tcx(), def_id, substs);
52             fields.len() == 1 &&
53                 fields.get(0).ident.name ==
54                     token::special_idents::unnamed_field.name &&
55                 type_is_immediate(ccx, fields.get(0).mt.ty)
56         }
57         _ => false
58     }
59 }
60
61 pub fn type_is_immediate(ccx: &CrateContext, ty: ty::t) -> bool {
62     use middle::trans::machine::llsize_of_alloc;
63     use middle::trans::type_of::sizing_type_of;
64     let tcx = ccx.tcx();
65     let simple = ty::type_is_scalar(ty) || ty::type_is_boxed(ty) ||
66         ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) ||
67         type_is_newtype_immediate(ccx, ty) || ty::type_is_bot(ty) ||
68         ty::type_is_simd(tcx, ty);
69     if simple && !ty::type_is_trait(ty) {
70         return true;
71     }
72     match ty::get(ty).sty {
73         ty::ty_bot => true,
74         ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) => {
75             let llty = sizing_type_of(ccx, ty);
76             llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type)
77         }
78         _ => type_is_zero_size(ccx, ty)
79     }
80 }
81
82 pub fn type_is_zero_size(ccx: &CrateContext, ty: ty::t) -> bool {
83     /*!
84      * Identify types which have size zero at runtime.
85      */
86
87     use middle::trans::machine::llsize_of_alloc;
88     use middle::trans::type_of::sizing_type_of;
89     let llty = sizing_type_of(ccx, ty);
90     llsize_of_alloc(ccx, llty) == 0
91 }
92
93 pub fn return_type_is_void(ccx: &CrateContext, ty: ty::t) -> bool {
94     /*!
95      * Identifies types which we declare to be equivalent to `void`
96      * in C for the purpose of function return types. These are
97      * `()`, bot, and uninhabited enums. Note that all such types
98      * are also zero-size, but not all zero-size types use a `void`
99      * return type (in order to aid with C ABI compatibility).
100      */
101
102     ty::type_is_nil(ty) || ty::type_is_bot(ty) || ty::type_is_empty(ccx.tcx(), ty)
103 }
104
105 /// Generates a unique symbol based off the name given. This is used to create
106 /// unique symbols for things like closures.
107 pub fn gensym_name(name: &str) -> PathElem {
108     let num = token::gensym(name);
109     // use one colon which will get translated to a period by the mangler, and
110     // we're guaranteed that `num` is globally unique for this crate.
111     PathName(token::gensym(format!("{}:{}", name, num).as_slice()))
112 }
113
114 pub struct tydesc_info {
115     pub ty: ty::t,
116     pub tydesc: ValueRef,
117     pub size: ValueRef,
118     pub align: ValueRef,
119     pub name: ValueRef,
120     pub visit_glue: Cell<Option<ValueRef>>,
121 }
122
123 /*
124  * A note on nomenclature of linking: "extern", "foreign", and "upcall".
125  *
126  * An "extern" is an LLVM symbol we wind up emitting an undefined external
127  * reference to. This means "we don't have the thing in this compilation unit,
128  * please make sure you link it in at runtime". This could be a reference to
129  * C code found in a C library, or rust code found in a rust crate.
130  *
131  * Most "externs" are implicitly declared (automatically) as a result of a
132  * user declaring an extern _module_ dependency; this causes the rust driver
133  * to locate an extern crate, scan its compilation metadata, and emit extern
134  * declarations for any symbols used by the declaring crate.
135  *
136  * A "foreign" is an extern that references C (or other non-rust ABI) code.
137  * There is no metadata to scan for extern references so in these cases either
138  * a header-digester like bindgen, or manual function prototypes, have to
139  * serve as declarators. So these are usually given explicitly as prototype
140  * declarations, in rust code, with ABI attributes on them noting which ABI to
141  * link via.
142  *
143  * An "upcall" is a foreign call generated by the compiler (not corresponding
144  * to any user-written call in the code) into the runtime library, to perform
145  * some helper task such as bringing a task to life, allocating memory, etc.
146  *
147  */
148
149 pub struct NodeInfo {
150     pub id: ast::NodeId,
151     pub span: Span,
152 }
153
154 pub fn expr_info(expr: &ast::Expr) -> NodeInfo {
155     NodeInfo { id: expr.id, span: expr.span }
156 }
157
158 pub struct BuilderRef_res {
159     pub b: BuilderRef,
160 }
161
162 impl Drop for BuilderRef_res {
163     fn drop(&mut self) {
164         unsafe {
165             llvm::LLVMDisposeBuilder(self.b);
166         }
167     }
168 }
169
170 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
171     BuilderRef_res {
172         b: b
173     }
174 }
175
176 pub type ExternMap = HashMap<String, ValueRef>;
177
178 // Here `self_ty` is the real type of the self parameter to this method. It
179 // will only be set in the case of default methods.
180 pub struct param_substs {
181     pub substs: subst::Substs,
182     pub vtables: typeck::vtable_res,
183 }
184
185 impl param_substs {
186     pub fn empty() -> param_substs {
187         param_substs {
188             substs: subst::Substs::trans_empty(),
189             vtables: subst::VecPerParamSpace::empty(),
190         }
191     }
192
193     pub fn validate(&self) {
194         assert!(self.substs.types.all(|t| !ty::type_needs_infer(*t)));
195     }
196 }
197
198 fn param_substs_to_string(this: &param_substs, tcx: &ty::ctxt) -> String {
199     format!("param_substs({})", this.substs.repr(tcx))
200 }
201
202 impl Repr for param_substs {
203     fn repr(&self, tcx: &ty::ctxt) -> String {
204         param_substs_to_string(self, tcx)
205     }
206 }
207
208 pub trait SubstP {
209     fn substp(&self, tcx: &ty::ctxt, param_substs: &param_substs)
210               -> Self;
211 }
212
213 impl<T:Subst+Clone> SubstP for T {
214     fn substp(&self, tcx: &ty::ctxt, substs: &param_substs) -> T {
215         self.subst(tcx, &substs.substs)
216     }
217 }
218
219 // work around bizarre resolve errors
220 pub type RvalueDatum = datum::Datum<datum::Rvalue>;
221 pub type LvalueDatum = datum::Datum<datum::Lvalue>;
222
223 // Function context.  Every LLVM function we create will have one of
224 // these.
225 pub struct FunctionContext<'a> {
226     // The ValueRef returned from a call to llvm::LLVMAddFunction; the
227     // address of the first instruction in the sequence of
228     // instructions for this function that will go in the .text
229     // section of the executable we're generating.
230     pub llfn: ValueRef,
231
232     // The environment argument in a closure.
233     pub llenv: Option<ValueRef>,
234
235     // The place to store the return value. If the return type is immediate,
236     // this is an alloca in the function. Otherwise, it's the hidden first
237     // parameter to the function. After function construction, this should
238     // always be Some.
239     pub llretptr: Cell<Option<ValueRef>>,
240
241     // These pub elements: "hoisted basic blocks" containing
242     // administrative activities that have to happen in only one place in
243     // the function, due to LLVM's quirks.
244     // A marker for the place where we want to insert the function's static
245     // allocas, so that LLVM will coalesce them into a single alloca call.
246     pub alloca_insert_pt: Cell<Option<ValueRef>>,
247     pub llreturn: Cell<Option<BasicBlockRef>>,
248
249     // The a value alloca'd for calls to upcalls.rust_personality. Used when
250     // outputting the resume instruction.
251     pub personality: Cell<Option<ValueRef>>,
252
253     // True if the caller expects this fn to use the out pointer to
254     // return. Either way, your code should write into llretptr, but if
255     // this value is false, llretptr will be a local alloca.
256     pub caller_expects_out_pointer: bool,
257
258     // Maps arguments to allocas created for them in llallocas.
259     pub llargs: RefCell<NodeMap<LvalueDatum>>,
260
261     // Maps the def_ids for local variables to the allocas created for
262     // them in llallocas.
263     pub lllocals: RefCell<NodeMap<LvalueDatum>>,
264
265     // Same as above, but for closure upvars
266     pub llupvars: RefCell<NodeMap<ValueRef>>,
267
268     // The NodeId of the function, or -1 if it doesn't correspond to
269     // a user-defined function.
270     pub id: ast::NodeId,
271
272     // If this function is being monomorphized, this contains the type
273     // substitutions used.
274     pub param_substs: &'a param_substs,
275
276     // The source span and nesting context where this function comes from, for
277     // error reporting and symbol generation.
278     pub span: Option<Span>,
279
280     // The arena that blocks are allocated from.
281     pub block_arena: &'a TypedArena<Block<'a>>,
282
283     // This function's enclosing crate context.
284     pub ccx: &'a CrateContext,
285
286     // Used and maintained by the debuginfo module.
287     pub debug_context: debuginfo::FunctionDebugContext,
288
289     // Cleanup scopes.
290     pub scopes: RefCell<Vec<cleanup::CleanupScope<'a>> >,
291 }
292
293 impl<'a> FunctionContext<'a> {
294     pub fn arg_pos(&self, arg: uint) -> uint {
295         let arg = self.env_arg_pos() + arg;
296         if self.llenv.is_some() {
297             arg + 1
298         } else {
299             arg
300         }
301     }
302
303     pub fn out_arg_pos(&self) -> uint {
304         assert!(self.caller_expects_out_pointer);
305         0u
306     }
307
308     pub fn env_arg_pos(&self) -> uint {
309         if self.caller_expects_out_pointer {
310             1u
311         } else {
312             0u
313         }
314     }
315
316     pub fn cleanup(&self) {
317         unsafe {
318             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
319                                                      .get()
320                                                      .unwrap());
321         }
322     }
323
324     pub fn get_llreturn(&self) -> BasicBlockRef {
325         if self.llreturn.get().is_none() {
326
327             self.llreturn.set(Some(unsafe {
328                 "return".with_c_str(|buf| {
329                     llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx, self.llfn, buf)
330                 })
331             }))
332         }
333
334         self.llreturn.get().unwrap()
335     }
336
337     pub fn new_block(&'a self,
338                      is_lpad: bool,
339                      name: &str,
340                      opt_node_id: Option<ast::NodeId>)
341                      -> &'a Block<'a> {
342         unsafe {
343             let llbb = name.with_c_str(|buf| {
344                     llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx,
345                                                         self.llfn,
346                                                         buf)
347                 });
348             Block::new(llbb, is_lpad, opt_node_id, self)
349         }
350     }
351
352     pub fn new_id_block(&'a self,
353                         name: &str,
354                         node_id: ast::NodeId)
355                         -> &'a Block<'a> {
356         self.new_block(false, name, Some(node_id))
357     }
358
359     pub fn new_temp_block(&'a self,
360                           name: &str)
361                           -> &'a Block<'a> {
362         self.new_block(false, name, None)
363     }
364
365     pub fn join_blocks(&'a self,
366                        id: ast::NodeId,
367                        in_cxs: &[&'a Block<'a>])
368                        -> &'a Block<'a> {
369         let out = self.new_id_block("join", id);
370         let mut reachable = false;
371         for bcx in in_cxs.iter() {
372             if !bcx.unreachable.get() {
373                 build::Br(*bcx, out.llbb);
374                 reachable = true;
375             }
376         }
377         if !reachable {
378             build::Unreachable(out);
379         }
380         return out;
381     }
382 }
383
384 // Basic block context.  We create a block context for each basic block
385 // (single-entry, single-exit sequence of instructions) we generate from Rust
386 // code.  Each basic block we generate is attached to a function, typically
387 // with many basic blocks per function.  All the basic blocks attached to a
388 // function are organized as a directed graph.
389 pub struct Block<'a> {
390     // The BasicBlockRef returned from a call to
391     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
392     // block to the function pointed to by llfn.  We insert
393     // instructions into that block by way of this block context.
394     // The block pointing to this one in the function's digraph.
395     pub llbb: BasicBlockRef,
396     pub terminated: Cell<bool>,
397     pub unreachable: Cell<bool>,
398
399     // Is this block part of a landing pad?
400     pub is_lpad: bool,
401
402     // AST node-id associated with this block, if any. Used for
403     // debugging purposes only.
404     pub opt_node_id: Option<ast::NodeId>,
405
406     // The function context for the function to which this block is
407     // attached.
408     pub fcx: &'a FunctionContext<'a>,
409 }
410
411 impl<'a> Block<'a> {
412     pub fn new<'a>(
413                llbb: BasicBlockRef,
414                is_lpad: bool,
415                opt_node_id: Option<ast::NodeId>,
416                fcx: &'a FunctionContext<'a>)
417                -> &'a Block<'a> {
418         fcx.block_arena.alloc(Block {
419             llbb: llbb,
420             terminated: Cell::new(false),
421             unreachable: Cell::new(false),
422             is_lpad: is_lpad,
423             opt_node_id: opt_node_id,
424             fcx: fcx
425         })
426     }
427
428     pub fn ccx(&self) -> &'a CrateContext { self.fcx.ccx }
429     pub fn tcx(&self) -> &'a ty::ctxt {
430         &self.fcx.ccx.tcx
431     }
432     pub fn sess(&self) -> &'a Session { self.fcx.ccx.sess() }
433
434     pub fn ident(&self, ident: Ident) -> String {
435         token::get_ident(ident).get().to_string()
436     }
437
438     pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
439         self.tcx().map.node_to_string(id).to_string()
440     }
441
442     pub fn expr_to_string(&self, e: &ast::Expr) -> String {
443         e.repr(self.tcx())
444     }
445
446     pub fn def(&self, nid: ast::NodeId) -> def::Def {
447         match self.tcx().def_map.borrow().find(&nid) {
448             Some(&v) => v,
449             None => {
450                 self.tcx().sess.bug(format!(
451                     "no def associated with node id {:?}", nid).as_slice());
452             }
453         }
454     }
455
456     pub fn val_to_string(&self, val: ValueRef) -> String {
457         self.ccx().tn.val_to_string(val)
458     }
459
460     pub fn llty_str(&self, ty: Type) -> String {
461         self.ccx().tn.type_to_string(ty)
462     }
463
464     pub fn ty_to_string(&self, t: ty::t) -> String {
465         t.repr(self.tcx())
466     }
467
468     pub fn to_str(&self) -> String {
469         let blk: *const Block = self;
470         format!("[block {}]", blk)
471     }
472 }
473
474 pub struct Result<'a> {
475     pub bcx: &'a Block<'a>,
476     pub val: ValueRef
477 }
478
479 impl<'a> Result<'a> {
480     pub fn new(bcx: &'a Block<'a>, val: ValueRef) -> Result<'a> {
481         Result {
482             bcx: bcx,
483             val: val,
484         }
485     }
486 }
487
488 pub fn val_ty(v: ValueRef) -> Type {
489     unsafe {
490         Type::from_ref(llvm::LLVMTypeOf(v))
491     }
492 }
493
494 // LLVM constant constructors.
495 pub fn C_null(t: Type) -> ValueRef {
496     unsafe {
497         llvm::LLVMConstNull(t.to_ref())
498     }
499 }
500
501 pub fn C_undef(t: Type) -> ValueRef {
502     unsafe {
503         llvm::LLVMGetUndef(t.to_ref())
504     }
505 }
506
507 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
508     unsafe {
509         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
510     }
511 }
512
513 pub fn C_floating(s: &str, t: Type) -> ValueRef {
514     unsafe {
515         s.with_c_str(|buf| llvm::LLVMConstRealOfString(t.to_ref(), buf))
516     }
517 }
518
519 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
520     C_struct(ccx, [], false)
521 }
522
523 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
524     C_integral(Type::i1(ccx), val as u64, false)
525 }
526
527 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
528     C_integral(Type::i32(ccx), i as u64, true)
529 }
530
531 pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef {
532     C_integral(Type::i64(ccx), i as u64, true)
533 }
534
535 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
536     C_integral(Type::i64(ccx), i, false)
537 }
538
539 pub fn C_int(ccx: &CrateContext, i: int) -> ValueRef {
540     C_integral(ccx.int_type, i as u64, true)
541 }
542
543 pub fn C_uint(ccx: &CrateContext, i: uint) -> ValueRef {
544     C_integral(ccx.int_type, i as u64, false)
545 }
546
547 pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef {
548     C_integral(Type::i8(ccx), i as u64, false)
549 }
550
551
552 // This is a 'c-like' raw string, which differs from
553 // our boxed-and-length-annotated strings.
554 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
555     unsafe {
556         match cx.const_cstr_cache.borrow().find(&s) {
557             Some(&llval) => return llval,
558             None => ()
559         }
560
561         let sc = llvm::LLVMConstStringInContext(cx.llcx,
562                                                 s.get().as_ptr() as *const c_char,
563                                                 s.get().len() as c_uint,
564                                                 !null_terminated as Bool);
565
566         let gsym = token::gensym("str");
567         let g = format!("str{}", gsym).with_c_str(|buf| {
568             llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
569         });
570         llvm::LLVMSetInitializer(g, sc);
571         llvm::LLVMSetGlobalConstant(g, True);
572         llvm::SetLinkage(g, llvm::InternalLinkage);
573
574         cx.const_cstr_cache.borrow_mut().insert(s, g);
575         g
576     }
577 }
578
579 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
580 // you will be kicked off fast isel. See issue #4352 for an example of this.
581 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
582     unsafe {
583         let len = s.get().len();
584         let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s, false),
585                                             Type::i8p(cx).to_ref());
586         C_named_struct(cx.tn.find_type("str_slice").unwrap(), [cs, C_uint(cx, len)])
587     }
588 }
589
590 pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef {
591     unsafe {
592         let len = data.len();
593         let lldata = C_bytes(cx, data);
594
595         let gsym = token::gensym("binary");
596         let g = format!("binary{}", gsym).with_c_str(|buf| {
597             llvm::LLVMAddGlobal(cx.llmod, val_ty(lldata).to_ref(), buf)
598         });
599         llvm::LLVMSetInitializer(g, lldata);
600         llvm::LLVMSetGlobalConstant(g, True);
601         llvm::SetLinkage(g, llvm::InternalLinkage);
602
603         let cs = llvm::LLVMConstPointerCast(g, Type::i8p(cx).to_ref());
604         C_struct(cx, [cs, C_uint(cx, len)], false)
605     }
606 }
607
608 pub fn C_struct(ccx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
609     unsafe {
610         llvm::LLVMConstStructInContext(ccx.llcx,
611                                        elts.as_ptr(), elts.len() as c_uint,
612                                        packed as Bool)
613     }
614 }
615
616 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
617     unsafe {
618         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
619     }
620 }
621
622 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
623     unsafe {
624         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
625     }
626 }
627
628 pub fn C_bytes(ccx: &CrateContext, bytes: &[u8]) -> ValueRef {
629     unsafe {
630         let ptr = bytes.as_ptr() as *const c_char;
631         return llvm::LLVMConstStringInContext(ccx.llcx, ptr, bytes.len() as c_uint, True);
632     }
633 }
634
635 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
636     unsafe {
637         llvm::LLVMGetParam(fndecl, param as c_uint)
638     }
639 }
640
641 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
642                   -> ValueRef {
643     unsafe {
644         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
645
646         debug!("const_get_elt(v={}, us={:?}, r={})",
647                cx.tn.val_to_string(v), us, cx.tn.val_to_string(r));
648
649         return r;
650     }
651 }
652
653 pub fn is_const(v: ValueRef) -> bool {
654     unsafe {
655         llvm::LLVMIsConstant(v) == True
656     }
657 }
658
659 pub fn const_to_int(v: ValueRef) -> c_longlong {
660     unsafe {
661         llvm::LLVMConstIntGetSExtValue(v)
662     }
663 }
664
665 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
666     unsafe {
667         llvm::LLVMConstIntGetZExtValue(v)
668     }
669 }
670
671 pub fn is_undef(val: ValueRef) -> bool {
672     unsafe {
673         llvm::LLVMIsUndef(val) != False
674     }
675 }
676
677 pub fn is_null(val: ValueRef) -> bool {
678     unsafe {
679         llvm::LLVMIsNull(val) != False
680     }
681 }
682
683 pub fn monomorphize_type(bcx: &Block, t: ty::t) -> ty::t {
684     t.subst(bcx.tcx(), &bcx.fcx.param_substs.substs)
685 }
686
687 pub fn node_id_type(bcx: &Block, id: ast::NodeId) -> ty::t {
688     let tcx = bcx.tcx();
689     let t = ty::node_id_to_type(tcx, id);
690     monomorphize_type(bcx, t)
691 }
692
693 pub fn expr_ty(bcx: &Block, ex: &ast::Expr) -> ty::t {
694     node_id_type(bcx, ex.id)
695 }
696
697 pub fn expr_ty_adjusted(bcx: &Block, ex: &ast::Expr) -> ty::t {
698     monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex))
699 }
700
701 // Key used to lookup values supplied for type parameters in an expr.
702 #[deriving(PartialEq)]
703 pub enum ExprOrMethodCall {
704     // Type parameters for a path like `None::<int>`
705     ExprId(ast::NodeId),
706
707     // Type parameters for a method call like `a.foo::<int>()`
708     MethodCall(typeck::MethodCall)
709 }
710
711 pub fn node_id_substs(bcx: &Block,
712                       node: ExprOrMethodCall)
713                       -> subst::Substs {
714     let tcx = bcx.tcx();
715
716     let substs = match node {
717         ExprId(id) => {
718             ty::node_id_item_substs(tcx, id).substs
719         }
720         MethodCall(method_call) => {
721             tcx.method_map.borrow().get(&method_call).substs.clone()
722         }
723     };
724
725     if substs.types.any(|t| ty::type_needs_infer(*t)) {
726         bcx.sess().bug(
727             format!("type parameters for node {:?} include inference types: \
728                      {}",
729                     node,
730                     substs.repr(bcx.tcx())).as_slice());
731     }
732
733     substs.substp(tcx, bcx.fcx.param_substs)
734 }
735
736 pub fn node_vtables(bcx: &Block, id: typeck::MethodCall)
737                  -> typeck::vtable_res {
738     bcx.tcx().vtable_map.borrow().find(&id).map(|vts| {
739         resolve_vtables_in_fn_ctxt(bcx.fcx, vts)
740     }).unwrap_or_else(|| subst::VecPerParamSpace::empty())
741 }
742
743 // Apply the typaram substitutions in the FunctionContext to some
744 // vtables. This should eliminate any vtable_params.
745 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext,
746                                   vts: &typeck::vtable_res)
747                                   -> typeck::vtable_res {
748     resolve_vtables_under_param_substs(fcx.ccx.tcx(),
749                                        fcx.param_substs,
750                                        vts)
751 }
752
753 pub fn resolve_vtables_under_param_substs(tcx: &ty::ctxt,
754                                           param_substs: &param_substs,
755                                           vts: &typeck::vtable_res)
756                                           -> typeck::vtable_res
757 {
758     vts.map(|ds| {
759         resolve_param_vtables_under_param_substs(tcx,
760                                                  param_substs,
761                                                  ds)
762     })
763 }
764
765 pub fn resolve_param_vtables_under_param_substs(tcx: &ty::ctxt,
766                                                 param_substs: &param_substs,
767                                                 ds: &typeck::vtable_param_res)
768                                                 -> typeck::vtable_param_res
769 {
770     ds.iter().map(|d| {
771         resolve_vtable_under_param_substs(tcx,
772                                           param_substs,
773                                           d)
774     }).collect()
775 }
776
777
778
779 pub fn resolve_vtable_under_param_substs(tcx: &ty::ctxt,
780                                          param_substs: &param_substs,
781                                          vt: &typeck::vtable_origin)
782                                          -> typeck::vtable_origin
783 {
784     match *vt {
785         typeck::vtable_static(trait_id, ref vtable_substs, ref sub) => {
786             let vtable_substs = vtable_substs.substp(tcx, param_substs);
787             typeck::vtable_static(
788                 trait_id,
789                 vtable_substs,
790                 resolve_vtables_under_param_substs(tcx, param_substs, sub))
791         }
792         typeck::vtable_param(n_param, n_bound) => {
793             find_vtable(tcx, param_substs, n_param, n_bound)
794         }
795         typeck::vtable_error => typeck::vtable_error
796     }
797 }
798
799 pub fn find_vtable(tcx: &ty::ctxt,
800                    ps: &param_substs,
801                    n_param: typeck::param_index,
802                    n_bound: uint)
803                    -> typeck::vtable_origin {
804     debug!("find_vtable(n_param={:?}, n_bound={}, ps={})",
805            n_param, n_bound, ps.repr(tcx));
806
807     let param_bounds = ps.vtables.get(n_param.space,
808                                       n_param.index);
809     param_bounds.get(n_bound).clone()
810 }
811
812 pub fn langcall(bcx: &Block,
813                 span: Option<Span>,
814                 msg: &str,
815                 li: LangItem)
816                 -> ast::DefId {
817     match bcx.tcx().lang_items.require(li) {
818         Ok(id) => id,
819         Err(s) => {
820             let msg = format!("{} {}", msg, s);
821             match span {
822                 Some(span) => bcx.tcx().sess.span_fatal(span, msg.as_slice()),
823                 None => bcx.tcx().sess.fatal(msg.as_slice()),
824             }
825         }
826     }
827 }