]> git.proxmox.com Git - rustc.git/blob - src/librustc_trans/trans/callee.rs
Imported Upstream version 1.0.0~beta.3
[rustc.git] / src / librustc_trans / trans / callee.rs
1 // Copyright 2012 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 //! Handles translation of callees as well as other call-related
12 //! things. Callees are a superset of normal rust values and sometimes
13 //! have different representations. In particular, top-level fn items
14 //! and methods are represented as just a fn ptr and not a full
15 //! closure.
16
17 pub use self::AutorefArg::*;
18 pub use self::CalleeData::*;
19 pub use self::CallArgs::*;
20
21 use arena::TypedArena;
22 use back::link;
23 use session;
24 use llvm::ValueRef;
25 use llvm::get_param;
26 use llvm;
27 use metadata::csearch;
28 use middle::def;
29 use middle::subst;
30 use middle::subst::{Subst, Substs};
31 use trans::adt;
32 use trans::base;
33 use trans::base::*;
34 use trans::build::*;
35 use trans::callee;
36 use trans::cleanup;
37 use trans::cleanup::CleanupMethods;
38 use trans::closure;
39 use trans::common::{self, Block, Result, NodeIdAndSpan, ExprId, CrateContext,
40 ExprOrMethodCall, FunctionContext, MethodCallKey};
41 use trans::consts;
42 use trans::datum::*;
43 use trans::debuginfo::{DebugLoc, ToDebugLoc};
44 use trans::declare;
45 use trans::expr;
46 use trans::glue;
47 use trans::inline;
48 use trans::foreign;
49 use trans::intrinsic;
50 use trans::meth;
51 use trans::monomorphize;
52 use trans::type_::Type;
53 use trans::type_of;
54 use middle::ty::{self, Ty};
55 use middle::ty::MethodCall;
56 use util::ppaux::Repr;
57 use util::ppaux::ty_to_string;
58
59 use syntax::abi as synabi;
60 use syntax::ast;
61 use syntax::ast_map;
62 use syntax::ptr::P;
63
64 #[derive(Copy, Clone)]
65 pub struct MethodData {
66 pub llfn: ValueRef,
67 pub llself: ValueRef,
68 }
69
70 pub enum CalleeData<'tcx> {
71 // Constructor for enum variant/tuple-like-struct
72 // i.e. Some, Ok
73 NamedTupleConstructor(subst::Substs<'tcx>, ty::Disr),
74
75 // Represents a (possibly monomorphized) top-level fn item or method
76 // item. Note that this is just the fn-ptr and is not a Rust closure
77 // value (which is a pair).
78 Fn(/* llfn */ ValueRef),
79
80 Intrinsic(ast::NodeId, subst::Substs<'tcx>),
81
82 TraitItem(MethodData)
83 }
84
85 pub struct Callee<'blk, 'tcx: 'blk> {
86 pub bcx: Block<'blk, 'tcx>,
87 pub data: CalleeData<'tcx>,
88 }
89
90 fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
91 -> Callee<'blk, 'tcx> {
92 let _icx = push_ctxt("trans_callee");
93 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
94
95 // pick out special kinds of expressions that can be called:
96 match expr.node {
97 ast::ExprPath(..) => {
98 return trans_def(bcx, bcx.def(expr.id), expr);
99 }
100 _ => {}
101 }
102
103 // any other expressions are closures:
104 return datum_callee(bcx, expr);
105
106 fn datum_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
107 -> Callee<'blk, 'tcx> {
108 let DatumBlock { bcx, datum, .. } = expr::trans(bcx, expr);
109 match datum.ty.sty {
110 ty::ty_bare_fn(..) => {
111 let llval = datum.to_llscalarish(bcx);
112 return Callee {
113 bcx: bcx,
114 data: Fn(llval),
115 };
116 }
117 _ => {
118 bcx.tcx().sess.span_bug(
119 expr.span,
120 &format!("type of callee is neither bare-fn nor closure: \
121 {}",
122 bcx.ty_to_string(datum.ty)));
123 }
124 }
125 }
126
127 fn fn_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, llfn: ValueRef)
128 -> Callee<'blk, 'tcx> {
129 return Callee {
130 bcx: bcx,
131 data: Fn(llfn),
132 };
133 }
134
135 fn trans_def<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
136 def: def::Def,
137 ref_expr: &ast::Expr)
138 -> Callee<'blk, 'tcx> {
139 debug!("trans_def(def={}, ref_expr={})", def.repr(bcx.tcx()), ref_expr.repr(bcx.tcx()));
140 let expr_ty = common::node_id_type(bcx, ref_expr.id);
141 match def {
142 def::DefFn(did, _) if {
143 let maybe_def_id = inline::get_local_instance(bcx.ccx(), did);
144 let maybe_ast_node = maybe_def_id.and_then(|def_id| bcx.tcx().map
145 .find(def_id.node));
146 match maybe_ast_node {
147 Some(ast_map::NodeStructCtor(_)) => true,
148 _ => false
149 }
150 } => {
151 let substs = common::node_id_substs(bcx.ccx(),
152 ExprId(ref_expr.id),
153 bcx.fcx.param_substs);
154 Callee {
155 bcx: bcx,
156 data: NamedTupleConstructor(substs, 0)
157 }
158 }
159 def::DefFn(did, _) if match expr_ty.sty {
160 ty::ty_bare_fn(_, ref f) => f.abi == synabi::RustIntrinsic,
161 _ => false
162 } => {
163 let substs = common::node_id_substs(bcx.ccx(),
164 ExprId(ref_expr.id),
165 bcx.fcx.param_substs);
166 let def_id = inline::maybe_instantiate_inline(bcx.ccx(), did);
167 Callee { bcx: bcx, data: Intrinsic(def_id.node, substs) }
168 }
169 def::DefFn(did, _) | def::DefMethod(did, def::FromImpl(_)) => {
170 fn_callee(bcx, trans_fn_ref(bcx.ccx(), did, ExprId(ref_expr.id),
171 bcx.fcx.param_substs).val)
172 }
173 def::DefMethod(meth_did, def::FromTrait(trait_did)) => {
174 fn_callee(bcx, meth::trans_static_method_callee(bcx.ccx(),
175 meth_did,
176 trait_did,
177 ref_expr.id,
178 bcx.fcx.param_substs).val)
179 }
180 def::DefVariant(tid, vid, _) => {
181 let vinfo = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
182 let substs = common::node_id_substs(bcx.ccx(),
183 ExprId(ref_expr.id),
184 bcx.fcx.param_substs);
185
186 // Nullary variants are not callable
187 assert!(!vinfo.args.is_empty());
188
189 Callee {
190 bcx: bcx,
191 data: NamedTupleConstructor(substs, vinfo.disr_val)
192 }
193 }
194 def::DefStruct(_) => {
195 let substs = common::node_id_substs(bcx.ccx(),
196 ExprId(ref_expr.id),
197 bcx.fcx.param_substs);
198 Callee {
199 bcx: bcx,
200 data: NamedTupleConstructor(substs, 0)
201 }
202 }
203 def::DefStatic(..) |
204 def::DefConst(..) |
205 def::DefLocal(..) |
206 def::DefUpvar(..) => {
207 datum_callee(bcx, ref_expr)
208 }
209 def::DefMod(..) | def::DefForeignMod(..) | def::DefTrait(..) |
210 def::DefTy(..) | def::DefPrimTy(..) | def::DefAssociatedTy(..) |
211 def::DefUse(..) | def::DefRegion(..) | def::DefLabel(..) |
212 def::DefTyParam(..) | def::DefSelfTy(..) => {
213 bcx.tcx().sess.span_bug(
214 ref_expr.span,
215 &format!("cannot translate def {:?} \
216 to a callable thing!", def));
217 }
218 }
219 }
220 }
221
222 /// Translates a reference (with id `ref_id`) to the fn/method with id `def_id` into a function
223 /// pointer. This may require monomorphization or inlining.
224 pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
225 def_id: ast::DefId,
226 node: ExprOrMethodCall,
227 param_substs: &'tcx subst::Substs<'tcx>)
228 -> Datum<'tcx, Rvalue> {
229 let _icx = push_ctxt("trans_fn_ref");
230
231 let substs = common::node_id_substs(ccx, node, param_substs);
232 debug!("trans_fn_ref(def_id={}, node={:?}, substs={})",
233 def_id.repr(ccx.tcx()),
234 node,
235 substs.repr(ccx.tcx()));
236 trans_fn_ref_with_substs(ccx, def_id, node, param_substs, substs)
237 }
238
239 fn trans_fn_ref_with_substs_to_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
240 def_id: ast::DefId,
241 ref_id: ast::NodeId,
242 substs: subst::Substs<'tcx>)
243 -> Callee<'blk, 'tcx> {
244 Callee {
245 bcx: bcx,
246 data: Fn(trans_fn_ref_with_substs(bcx.ccx(),
247 def_id,
248 ExprId(ref_id),
249 bcx.fcx.param_substs,
250 substs).val),
251 }
252 }
253
254 /// Translates an adapter that implements the `Fn` trait for a fn
255 /// pointer. This is basically the equivalent of something like:
256 ///
257 /// ```
258 /// impl<'a> Fn(&'a int) -> &'a int for fn(&int) -> &int {
259 /// extern "rust-abi" fn call(&self, args: (&'a int,)) -> &'a int {
260 /// (*self)(args.0)
261 /// }
262 /// }
263 /// ```
264 ///
265 /// but for the bare function type given.
266 pub fn trans_fn_pointer_shim<'a, 'tcx>(
267 ccx: &'a CrateContext<'a, 'tcx>,
268 closure_kind: ty::ClosureKind,
269 bare_fn_ty: Ty<'tcx>)
270 -> ValueRef
271 {
272 let _icx = push_ctxt("trans_fn_pointer_shim");
273 let tcx = ccx.tcx();
274
275 // Normalize the type for better caching.
276 let bare_fn_ty = common::erase_regions(tcx, &bare_fn_ty);
277
278 // If this is an impl of `Fn` or `FnMut` trait, the receiver is `&self`.
279 let is_by_ref = match closure_kind {
280 ty::FnClosureKind | ty::FnMutClosureKind => true,
281 ty::FnOnceClosureKind => false,
282 };
283 let bare_fn_ty_maybe_ref = if is_by_ref {
284 ty::mk_imm_rptr(tcx, tcx.mk_region(ty::ReStatic), bare_fn_ty)
285 } else {
286 bare_fn_ty
287 };
288
289 // Check if we already trans'd this shim.
290 match ccx.fn_pointer_shims().borrow().get(&bare_fn_ty_maybe_ref) {
291 Some(&llval) => { return llval; }
292 None => { }
293 }
294
295 debug!("trans_fn_pointer_shim(bare_fn_ty={})",
296 bare_fn_ty.repr(tcx));
297
298 // Construct the "tuply" version of `bare_fn_ty`. It takes two arguments: `self`,
299 // which is the fn pointer, and `args`, which is the arguments tuple.
300 let (opt_def_id, sig) =
301 match bare_fn_ty.sty {
302 ty::ty_bare_fn(opt_def_id,
303 &ty::BareFnTy { unsafety: ast::Unsafety::Normal,
304 abi: synabi::Rust,
305 ref sig }) => {
306 (opt_def_id, sig)
307 }
308
309 _ => {
310 tcx.sess.bug(&format!("trans_fn_pointer_shim invoked on invalid type: {}",
311 bare_fn_ty.repr(tcx)));
312 }
313 };
314 let sig = ty::erase_late_bound_regions(tcx, sig);
315 let tuple_input_ty = ty::mk_tup(tcx, sig.inputs.to_vec());
316 let tuple_fn_ty = ty::mk_bare_fn(tcx,
317 opt_def_id,
318 tcx.mk_bare_fn(ty::BareFnTy {
319 unsafety: ast::Unsafety::Normal,
320 abi: synabi::RustCall,
321 sig: ty::Binder(ty::FnSig {
322 inputs: vec![bare_fn_ty_maybe_ref,
323 tuple_input_ty],
324 output: sig.output,
325 variadic: false
326 })}));
327 debug!("tuple_fn_ty: {}", tuple_fn_ty.repr(tcx));
328
329 //
330 let function_name = link::mangle_internal_name_by_type_and_seq(ccx, bare_fn_ty,
331 "fn_pointer_shim");
332 let llfn = declare::declare_internal_rust_fn(ccx, &function_name[..], tuple_fn_ty);
333
334 //
335 let empty_substs = tcx.mk_substs(Substs::trans_empty());
336 let (block_arena, fcx): (TypedArena<_>, FunctionContext);
337 block_arena = TypedArena::new();
338 fcx = new_fn_ctxt(ccx,
339 llfn,
340 ast::DUMMY_NODE_ID,
341 false,
342 sig.output,
343 empty_substs,
344 None,
345 &block_arena);
346 let mut bcx = init_function(&fcx, false, sig.output);
347
348 // the first argument (`self`) will be ptr to the the fn pointer
349 let llfnpointer = if is_by_ref {
350 Load(bcx, get_param(fcx.llfn, fcx.arg_pos(0) as u32))
351 } else {
352 get_param(fcx.llfn, fcx.arg_pos(0) as u32)
353 };
354
355 // the remaining arguments will be the untupled values
356 let llargs: Vec<_> =
357 sig.inputs.iter()
358 .enumerate()
359 .map(|(i, _)| get_param(fcx.llfn, fcx.arg_pos(i+1) as u32))
360 .collect();
361 assert!(!fcx.needs_ret_allocas);
362
363 let dest = fcx.llretslotptr.get().map(|_|
364 expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot"))
365 );
366
367 bcx = trans_call_inner(bcx,
368 DebugLoc::None,
369 bare_fn_ty,
370 |bcx, _| Callee { bcx: bcx, data: Fn(llfnpointer) },
371 ArgVals(&llargs[..]),
372 dest).bcx;
373
374 finish_fn(&fcx, bcx, sig.output, DebugLoc::None);
375
376 ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty_maybe_ref, llfn);
377
378 llfn
379 }
380
381 /// Translates a reference to a fn/method item, monomorphizing and
382 /// inlining as it goes.
383 ///
384 /// # Parameters
385 ///
386 /// - `ccx`: the crate context
387 /// - `def_id`: def id of the fn or method item being referenced
388 /// - `node`: node id of the reference to the fn/method, if applicable.
389 /// This parameter may be zero; but, if so, the resulting value may not
390 /// have the right type, so it must be cast before being used.
391 /// - `param_substs`: if the `node` is in a polymorphic function, these
392 /// are the substitutions required to monomorphize its type
393 /// - `substs`: values for each of the fn/method's parameters
394 pub fn trans_fn_ref_with_substs<'a, 'tcx>(
395 ccx: &CrateContext<'a, 'tcx>,
396 def_id: ast::DefId,
397 node: ExprOrMethodCall,
398 param_substs: &'tcx subst::Substs<'tcx>,
399 substs: subst::Substs<'tcx>)
400 -> Datum<'tcx, Rvalue>
401 {
402 let _icx = push_ctxt("trans_fn_ref_with_substs");
403 let tcx = ccx.tcx();
404
405 debug!("trans_fn_ref_with_substs(def_id={}, node={:?}, \
406 param_substs={}, substs={})",
407 def_id.repr(tcx),
408 node,
409 param_substs.repr(tcx),
410 substs.repr(tcx));
411
412 assert!(substs.types.all(|t| !ty::type_needs_infer(*t)));
413 assert!(substs.types.all(|t| !ty::type_has_escaping_regions(*t)));
414 let substs = substs.erase_regions();
415
416 // Load the info for the appropriate trait if necessary.
417 match ty::trait_of_item(tcx, def_id) {
418 None => {}
419 Some(trait_id) => {
420 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
421 }
422 }
423
424 // We need to do a bunch of special handling for default methods.
425 // We need to modify the def_id and our substs in order to monomorphize
426 // the function.
427 let (is_default, def_id, substs) = match ty::provided_source(tcx, def_id) {
428 None => {
429 (false, def_id, tcx.mk_substs(substs))
430 }
431 Some(source_id) => {
432 // There are two relevant substitutions when compiling
433 // default methods. First, there is the substitution for
434 // the type parameters of the impl we are using and the
435 // method we are calling. This substitution is the substs
436 // argument we already have.
437 // In order to compile a default method, though, we need
438 // to consider another substitution: the substitution for
439 // the type parameters on trait; the impl we are using
440 // implements the trait at some particular type
441 // parameters, and we need to substitute for those first.
442 // So, what we need to do is find this substitution and
443 // compose it with the one we already have.
444
445 let impl_id = ty::impl_or_trait_item(tcx, def_id).container()
446 .id();
447 let impl_or_trait_item = ty::impl_or_trait_item(tcx, source_id);
448 match impl_or_trait_item {
449 ty::MethodTraitItem(method) => {
450 let trait_ref = ty::impl_trait_ref(tcx, impl_id).unwrap();
451
452 // Compute the first substitution
453 let first_subst =
454 ty::make_substs_for_receiver_types(tcx, &*trait_ref, &*method)
455 .erase_regions();
456
457 // And compose them
458 let new_substs = tcx.mk_substs(first_subst.subst(tcx, &substs));
459
460 debug!("trans_fn_with_vtables - default method: \
461 substs = {}, trait_subst = {}, \
462 first_subst = {}, new_subst = {}",
463 substs.repr(tcx), trait_ref.substs.repr(tcx),
464 first_subst.repr(tcx), new_substs.repr(tcx));
465
466 (true, source_id, new_substs)
467 }
468 ty::TypeTraitItem(_) => {
469 tcx.sess.bug("trans_fn_ref_with_vtables() tried \
470 to translate an associated type?!")
471 }
472 }
473 }
474 };
475
476 // If this is a closure, redirect to it.
477 match closure::get_or_create_declaration_if_closure(ccx, def_id, substs) {
478 None => {}
479 Some(llfn) => return llfn,
480 }
481
482 // Check whether this fn has an inlined copy and, if so, redirect
483 // def_id to the local id of the inlined copy.
484 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
485
486 // We must monomorphise if the fn has type parameters, is a default method,
487 // or is a named tuple constructor.
488 let must_monomorphise = if !substs.types.is_empty() || is_default {
489 true
490 } else if def_id.krate == ast::LOCAL_CRATE {
491 let map_node = session::expect(
492 ccx.sess(),
493 tcx.map.find(def_id.node),
494 || "local item should be in ast map".to_string());
495
496 match map_node {
497 ast_map::NodeVariant(v) => match v.node.kind {
498 ast::TupleVariantKind(ref args) => !args.is_empty(),
499 _ => false
500 },
501 ast_map::NodeStructCtor(_) => true,
502 _ => false
503 }
504 } else {
505 false
506 };
507
508 // Create a monomorphic version of generic functions
509 if must_monomorphise {
510 // Should be either intra-crate or inlined.
511 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
512
513 let opt_ref_id = match node {
514 ExprId(id) => if id != 0 { Some(id) } else { None },
515 MethodCallKey(_) => None,
516 };
517
518 let (val, fn_ty, must_cast) =
519 monomorphize::monomorphic_fn(ccx, def_id, substs, opt_ref_id);
520 if must_cast && node != ExprId(0) {
521 // Monotype of the REFERENCE to the function (type params
522 // are subst'd)
523 let ref_ty = match node {
524 ExprId(id) => ty::node_id_to_type(tcx, id),
525 MethodCallKey(method_call) => {
526 tcx.method_map.borrow().get(&method_call).unwrap().ty
527 }
528 };
529 let ref_ty = monomorphize::apply_param_substs(tcx,
530 param_substs,
531 &ref_ty);
532 let llptrty = type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to();
533 if llptrty != common::val_ty(val) {
534 let val = consts::ptrcast(val, llptrty);
535 return Datum::new(val, ref_ty, Rvalue::new(ByValue));
536 }
537 }
538 return Datum::new(val, fn_ty, Rvalue::new(ByValue));
539 }
540
541 // Type scheme of the function item (may have type params)
542 let fn_type_scheme = ty::lookup_item_type(tcx, def_id);
543 let fn_type = monomorphize::normalize_associated_type(tcx, &fn_type_scheme.ty);
544
545 // Find the actual function pointer.
546 let mut val = {
547 if def_id.krate == ast::LOCAL_CRATE {
548 // Internal reference.
549 get_item_val(ccx, def_id.node)
550 } else {
551 // External reference.
552 trans_external_path(ccx, def_id, fn_type)
553 }
554 };
555
556 // This is subtle and surprising, but sometimes we have to bitcast
557 // the resulting fn pointer. The reason has to do with external
558 // functions. If you have two crates that both bind the same C
559 // library, they may not use precisely the same types: for
560 // example, they will probably each declare their own structs,
561 // which are distinct types from LLVM's point of view (nominal
562 // types).
563 //
564 // Now, if those two crates are linked into an application, and
565 // they contain inlined code, you can wind up with a situation
566 // where both of those functions wind up being loaded into this
567 // application simultaneously. In that case, the same function
568 // (from LLVM's point of view) requires two types. But of course
569 // LLVM won't allow one function to have two types.
570 //
571 // What we currently do, therefore, is declare the function with
572 // one of the two types (whichever happens to come first) and then
573 // bitcast as needed when the function is referenced to make sure
574 // it has the type we expect.
575 //
576 // This can occur on either a crate-local or crate-external
577 // reference. It also occurs when testing libcore and in some
578 // other weird situations. Annoying.
579 let llty = type_of::type_of_fn_from_ty(ccx, fn_type);
580 let llptrty = llty.ptr_to();
581 if common::val_ty(val) != llptrty {
582 debug!("trans_fn_ref_with_vtables(): casting pointer!");
583 val = consts::ptrcast(val, llptrty);
584 } else {
585 debug!("trans_fn_ref_with_vtables(): not casting pointer!");
586 }
587
588 Datum::new(val, fn_type, Rvalue::new(ByValue))
589 }
590
591 // ______________________________________________________________________
592 // Translating calls
593
594 pub fn trans_call<'a, 'blk, 'tcx>(in_cx: Block<'blk, 'tcx>,
595 call_expr: &ast::Expr,
596 f: &ast::Expr,
597 args: CallArgs<'a, 'tcx>,
598 dest: expr::Dest)
599 -> Block<'blk, 'tcx> {
600 let _icx = push_ctxt("trans_call");
601 trans_call_inner(in_cx,
602 call_expr.debug_loc(),
603 common::expr_ty_adjusted(in_cx, f),
604 |cx, _| trans(cx, f),
605 args,
606 Some(dest)).bcx
607 }
608
609 pub fn trans_method_call<'a, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
610 call_expr: &ast::Expr,
611 rcvr: &ast::Expr,
612 args: CallArgs<'a, 'tcx>,
613 dest: expr::Dest)
614 -> Block<'blk, 'tcx> {
615 let _icx = push_ctxt("trans_method_call");
616 debug!("trans_method_call(call_expr={})", call_expr.repr(bcx.tcx()));
617 let method_call = MethodCall::expr(call_expr.id);
618 let method_ty = match bcx.tcx().method_map.borrow().get(&method_call) {
619 Some(method) => match method.origin {
620 ty::MethodTraitObject(_) => match method.ty.sty {
621 ty::ty_bare_fn(_, ref fty) => {
622 ty::mk_bare_fn(bcx.tcx(), None, meth::opaque_method_ty(bcx.tcx(), fty))
623 }
624 _ => method.ty
625 },
626 _ => method.ty
627 },
628 None => panic!("method not found in trans_method_call")
629 };
630 trans_call_inner(
631 bcx,
632 call_expr.debug_loc(),
633 common::monomorphize_type(bcx, method_ty),
634 |cx, arg_cleanup_scope| {
635 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
636 },
637 args,
638 Some(dest)).bcx
639 }
640
641 pub fn trans_lang_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
642 did: ast::DefId,
643 args: &[ValueRef],
644 dest: Option<expr::Dest>,
645 debug_loc: DebugLoc)
646 -> Result<'blk, 'tcx> {
647 let fty = if did.krate == ast::LOCAL_CRATE {
648 ty::node_id_to_type(bcx.tcx(), did.node)
649 } else {
650 csearch::get_type(bcx.tcx(), did).ty
651 };
652 callee::trans_call_inner(bcx,
653 debug_loc,
654 fty,
655 |bcx, _| {
656 trans_fn_ref_with_substs_to_callee(bcx,
657 did,
658 0,
659 subst::Substs::trans_empty())
660 },
661 ArgVals(args),
662 dest)
663 }
664
665 /// This behemoth of a function translates function calls. Unfortunately, in order to generate more
666 /// efficient LLVM output at -O0, it has quite a complex signature (refactoring this into two
667 /// functions seems like a good idea).
668 ///
669 /// In particular, for lang items, it is invoked with a dest of None, and in that case the return
670 /// value contains the result of the fn. The lang item must not return a structural type or else
671 /// all heck breaks loose.
672 ///
673 /// For non-lang items, `dest` is always Some, and hence the result is written into memory
674 /// somewhere. Nonetheless we return the actual return value of the function.
675 pub fn trans_call_inner<'a, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
676 debug_loc: DebugLoc,
677 callee_ty: Ty<'tcx>,
678 get_callee: F,
679 args: CallArgs<'a, 'tcx>,
680 dest: Option<expr::Dest>)
681 -> Result<'blk, 'tcx> where
682 F: FnOnce(Block<'blk, 'tcx>, cleanup::ScopeId) -> Callee<'blk, 'tcx>,
683 {
684 // Introduce a temporary cleanup scope that will contain cleanups
685 // for the arguments while they are being evaluated. The purpose
686 // this cleanup is to ensure that, should a panic occur while
687 // evaluating argument N, the values for arguments 0...N-1 are all
688 // cleaned up. If no panic occurs, the values are handed off to
689 // the callee, and hence none of the cleanups in this temporary
690 // scope will ever execute.
691 let fcx = bcx.fcx;
692 let ccx = fcx.ccx;
693 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
694
695 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
696 let mut bcx = callee.bcx;
697
698 let (abi, ret_ty) = match callee_ty.sty {
699 ty::ty_bare_fn(_, ref f) => {
700 let output = ty::erase_late_bound_regions(bcx.tcx(), &f.sig.output());
701 (f.abi, output)
702 }
703 _ => panic!("expected bare rust fn or closure in trans_call_inner")
704 };
705
706 let (llfn, llenv, llself) = match callee.data {
707 Fn(llfn) => {
708 (llfn, None, None)
709 }
710 TraitItem(d) => {
711 (d.llfn, None, Some(d.llself))
712 }
713 Intrinsic(node, substs) => {
714 assert!(abi == synabi::RustIntrinsic);
715 assert!(dest.is_some());
716
717 let call_info = match debug_loc {
718 DebugLoc::At(id, span) => NodeIdAndSpan { id: id, span: span },
719 DebugLoc::None => {
720 bcx.sess().bug("No call info for intrinsic call?")
721 }
722 };
723
724 return intrinsic::trans_intrinsic_call(bcx, node, callee_ty,
725 arg_cleanup_scope, args,
726 dest.unwrap(), substs,
727 call_info);
728 }
729 NamedTupleConstructor(substs, disr) => {
730 assert!(dest.is_some());
731 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
732
733 let ctor_ty = callee_ty.subst(bcx.tcx(), &substs);
734 return base::trans_named_tuple_constructor(bcx,
735 ctor_ty,
736 disr,
737 args,
738 dest.unwrap(),
739 debug_loc);
740 }
741 };
742
743 // Intrinsics should not become actual functions.
744 // We trans them in place in `trans_intrinsic_call`
745 assert!(abi != synabi::RustIntrinsic);
746
747 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustCall;
748
749 // Generate a location to store the result. If the user does
750 // not care about the result, just make a stack slot.
751 let opt_llretslot = dest.and_then(|dest| match dest {
752 expr::SaveIn(dst) => Some(dst),
753 expr::Ignore => {
754 let ret_ty = match ret_ty {
755 ty::FnConverging(ret_ty) => ret_ty,
756 ty::FnDiverging => ty::mk_nil(ccx.tcx())
757 };
758 if !is_rust_fn ||
759 type_of::return_uses_outptr(ccx, ret_ty) ||
760 bcx.fcx.type_needs_drop(ret_ty) {
761 // Push the out-pointer if we use an out-pointer for this
762 // return type, otherwise push "undef".
763 if common::type_is_zero_size(ccx, ret_ty) {
764 let llty = type_of::type_of(ccx, ret_ty);
765 Some(common::C_undef(llty.ptr_to()))
766 } else {
767 Some(alloc_ty(bcx, ret_ty, "__llret"))
768 }
769 } else {
770 None
771 }
772 }
773 });
774
775 let mut llresult = unsafe {
776 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
777 };
778
779 // The code below invokes the function, using either the Rust
780 // conventions (if it is a rust fn) or the native conventions
781 // (otherwise). The important part is that, when all is said
782 // and done, either the return value of the function will have been
783 // written in opt_llretslot (if it is Some) or `llresult` will be
784 // set appropriately (otherwise).
785 if is_rust_fn {
786 let mut llargs = Vec::new();
787
788 if let (ty::FnConverging(ret_ty), Some(mut llretslot)) = (ret_ty, opt_llretslot) {
789 if type_of::return_uses_outptr(ccx, ret_ty) {
790 let llformal_ret_ty = type_of::type_of(ccx, ret_ty).ptr_to();
791 let llret_ty = common::val_ty(llretslot);
792 if llformal_ret_ty != llret_ty {
793 // this could happen due to e.g. subtyping
794 debug!("casting actual return type ({}) to match formal ({})",
795 bcx.llty_str(llret_ty), bcx.llty_str(llformal_ret_ty));
796 llretslot = PointerCast(bcx, llretslot, llformal_ret_ty);
797 }
798 llargs.push(llretslot);
799 }
800 }
801
802 // Push the environment (or a trait object's self).
803 match (llenv, llself) {
804 (Some(llenv), None) => llargs.push(llenv),
805 (None, Some(llself)) => llargs.push(llself),
806 _ => {}
807 }
808
809 // Push the arguments.
810 bcx = trans_args(bcx,
811 args,
812 callee_ty,
813 &mut llargs,
814 cleanup::CustomScope(arg_cleanup_scope),
815 llself.is_some(),
816 abi);
817
818 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
819
820 // Invoke the actual rust fn and update bcx/llresult.
821 let (llret, b) = base::invoke(bcx,
822 llfn,
823 &llargs[..],
824 callee_ty,
825 debug_loc);
826 bcx = b;
827 llresult = llret;
828
829 // If the Rust convention for this type is return via
830 // the return value, copy it into llretslot.
831 match (opt_llretslot, ret_ty) {
832 (Some(llretslot), ty::FnConverging(ret_ty)) => {
833 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
834 !common::type_is_zero_size(bcx.ccx(), ret_ty)
835 {
836 store_ty(bcx, llret, llretslot, ret_ty)
837 }
838 }
839 (_, _) => {}
840 }
841 } else {
842 // Lang items are the only case where dest is None, and
843 // they are always Rust fns.
844 assert!(dest.is_some());
845
846 let mut llargs = Vec::new();
847 let arg_tys = match args {
848 ArgExprs(a) => a.iter().map(|x| common::expr_ty(bcx, &**x)).collect(),
849 _ => panic!("expected arg exprs.")
850 };
851 bcx = trans_args(bcx,
852 args,
853 callee_ty,
854 &mut llargs,
855 cleanup::CustomScope(arg_cleanup_scope),
856 false,
857 abi);
858 fcx.scopes.borrow_mut().last_mut().unwrap().drop_non_lifetime_clean();
859
860 bcx = foreign::trans_native_call(bcx,
861 callee_ty,
862 llfn,
863 opt_llretslot.unwrap(),
864 &llargs[..],
865 arg_tys,
866 debug_loc);
867 }
868
869 fcx.pop_and_trans_custom_cleanup_scope(bcx, arg_cleanup_scope);
870
871 // If the caller doesn't care about the result of this fn call,
872 // drop the temporary slot we made.
873 match (dest, opt_llretslot, ret_ty) {
874 (Some(expr::Ignore), Some(llretslot), ty::FnConverging(ret_ty)) => {
875 // drop the value if it is not being saved.
876 bcx = glue::drop_ty(bcx,
877 llretslot,
878 ret_ty,
879 debug_loc);
880 call_lifetime_end(bcx, llretslot);
881 }
882 _ => {}
883 }
884
885 if ret_ty == ty::FnDiverging {
886 Unreachable(bcx);
887 }
888
889 Result::new(bcx, llresult)
890 }
891
892 pub enum CallArgs<'a, 'tcx> {
893 // Supply value of arguments as a list of expressions that must be
894 // translated. This is used in the common case of `foo(bar, qux)`.
895 ArgExprs(&'a [P<ast::Expr>]),
896
897 // Supply value of arguments as a list of LLVM value refs; frequently
898 // used with lang items and so forth, when the argument is an internal
899 // value.
900 ArgVals(&'a [ValueRef]),
901
902 // For overloaded operators: `(lhs, Vec(rhs, rhs_id), autoref)`. `lhs`
903 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
904 // the right-hand-side arguments (if any). `autoref` indicates whether the `rhs`
905 // arguments should be auto-referenced
906 ArgOverloadedOp(Datum<'tcx, Expr>, Vec<(Datum<'tcx, Expr>, ast::NodeId)>, bool),
907
908 // Supply value of arguments as a list of expressions that must be
909 // translated, for overloaded call operators.
910 ArgOverloadedCall(Vec<&'a ast::Expr>),
911 }
912
913 fn trans_args_under_call_abi<'blk, 'tcx>(
914 mut bcx: Block<'blk, 'tcx>,
915 arg_exprs: &[P<ast::Expr>],
916 fn_ty: Ty<'tcx>,
917 llargs: &mut Vec<ValueRef>,
918 arg_cleanup_scope: cleanup::ScopeId,
919 ignore_self: bool)
920 -> Block<'blk, 'tcx>
921 {
922 let args =
923 ty::erase_late_bound_regions(
924 bcx.tcx(), &ty::ty_fn_args(fn_ty));
925
926 // Translate the `self` argument first.
927 if !ignore_self {
928 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &*arg_exprs[0]));
929 llargs.push(unpack_result!(bcx, {
930 trans_arg_datum(bcx,
931 args[0],
932 arg_datum,
933 arg_cleanup_scope,
934 DontAutorefArg)
935 }))
936 }
937
938 // Now untuple the rest of the arguments.
939 let tuple_expr = &arg_exprs[1];
940 let tuple_type = common::node_id_type(bcx, tuple_expr.id);
941
942 match tuple_type.sty {
943 ty::ty_tup(ref field_types) => {
944 let tuple_datum = unpack_datum!(bcx,
945 expr::trans(bcx, &**tuple_expr));
946 let tuple_lvalue_datum =
947 unpack_datum!(bcx,
948 tuple_datum.to_lvalue_datum(bcx,
949 "args",
950 tuple_expr.id));
951 let repr = adt::represent_type(bcx.ccx(), tuple_type);
952 let repr_ptr = &*repr;
953 llargs.extend(field_types.iter().enumerate().map(|(i, field_type)| {
954 let arg_datum = tuple_lvalue_datum.get_element(
955 bcx,
956 field_type,
957 |srcval| {
958 adt::trans_field_ptr(bcx, repr_ptr, srcval, 0, i)
959 }).to_expr_datum();
960 unpack_result!(bcx, trans_arg_datum(
961 bcx,
962 field_type,
963 arg_datum,
964 arg_cleanup_scope,
965 DontAutorefArg)
966 )
967 }));
968 }
969 _ => {
970 bcx.sess().span_bug(tuple_expr.span,
971 "argument to `.call()` wasn't a tuple?!")
972 }
973 };
974
975 bcx
976 }
977
978 fn trans_overloaded_call_args<'blk, 'tcx>(
979 mut bcx: Block<'blk, 'tcx>,
980 arg_exprs: Vec<&ast::Expr>,
981 fn_ty: Ty<'tcx>,
982 llargs: &mut Vec<ValueRef>,
983 arg_cleanup_scope: cleanup::ScopeId,
984 ignore_self: bool)
985 -> Block<'blk, 'tcx> {
986 // Translate the `self` argument first.
987 let arg_tys = ty::erase_late_bound_regions(bcx.tcx(), &ty::ty_fn_args(fn_ty));
988 if !ignore_self {
989 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_exprs[0]));
990 llargs.push(unpack_result!(bcx, {
991 trans_arg_datum(bcx,
992 arg_tys[0],
993 arg_datum,
994 arg_cleanup_scope,
995 DontAutorefArg)
996 }))
997 }
998
999 // Now untuple the rest of the arguments.
1000 let tuple_type = arg_tys[1];
1001 match tuple_type.sty {
1002 ty::ty_tup(ref field_types) => {
1003 for (i, &field_type) in field_types.iter().enumerate() {
1004 let arg_datum =
1005 unpack_datum!(bcx, expr::trans(bcx, arg_exprs[i + 1]));
1006 llargs.push(unpack_result!(bcx, {
1007 trans_arg_datum(bcx,
1008 field_type,
1009 arg_datum,
1010 arg_cleanup_scope,
1011 DontAutorefArg)
1012 }))
1013 }
1014 }
1015 _ => {
1016 bcx.sess().span_bug(arg_exprs[0].span,
1017 "argument to `.call()` wasn't a tuple?!")
1018 }
1019 };
1020
1021 bcx
1022 }
1023
1024 pub fn trans_args<'a, 'blk, 'tcx>(cx: Block<'blk, 'tcx>,
1025 args: CallArgs<'a, 'tcx>,
1026 fn_ty: Ty<'tcx>,
1027 llargs: &mut Vec<ValueRef>,
1028 arg_cleanup_scope: cleanup::ScopeId,
1029 ignore_self: bool,
1030 abi: synabi::Abi)
1031 -> Block<'blk, 'tcx> {
1032 debug!("trans_args(abi={})", abi);
1033
1034 let _icx = push_ctxt("trans_args");
1035 let arg_tys = ty::erase_late_bound_regions(cx.tcx(), &ty::ty_fn_args(fn_ty));
1036 let variadic = ty::fn_is_variadic(fn_ty);
1037
1038 let mut bcx = cx;
1039
1040 // First we figure out the caller's view of the types of the arguments.
1041 // This will be needed if this is a generic call, because the callee has
1042 // to cast her view of the arguments to the caller's view.
1043 match args {
1044 ArgExprs(arg_exprs) => {
1045 if abi == synabi::RustCall {
1046 // This is only used for direct calls to the `call`,
1047 // `call_mut` or `call_once` functions.
1048 return trans_args_under_call_abi(cx,
1049 arg_exprs,
1050 fn_ty,
1051 llargs,
1052 arg_cleanup_scope,
1053 ignore_self)
1054 }
1055
1056 let num_formal_args = arg_tys.len();
1057 for (i, arg_expr) in arg_exprs.iter().enumerate() {
1058 if i == 0 && ignore_self {
1059 continue;
1060 }
1061 let arg_ty = if i >= num_formal_args {
1062 assert!(variadic);
1063 common::expr_ty_adjusted(cx, &**arg_expr)
1064 } else {
1065 arg_tys[i]
1066 };
1067
1068 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, &**arg_expr));
1069 llargs.push(unpack_result!(bcx, {
1070 trans_arg_datum(bcx, arg_ty, arg_datum,
1071 arg_cleanup_scope,
1072 DontAutorefArg)
1073 }));
1074 }
1075 }
1076 ArgOverloadedCall(arg_exprs) => {
1077 return trans_overloaded_call_args(cx,
1078 arg_exprs,
1079 fn_ty,
1080 llargs,
1081 arg_cleanup_scope,
1082 ignore_self)
1083 }
1084 ArgOverloadedOp(lhs, rhs, autoref) => {
1085 assert!(!variadic);
1086
1087 llargs.push(unpack_result!(bcx, {
1088 trans_arg_datum(bcx, arg_tys[0], lhs,
1089 arg_cleanup_scope,
1090 DontAutorefArg)
1091 }));
1092
1093 assert_eq!(arg_tys.len(), 1 + rhs.len());
1094 for (rhs, rhs_id) in rhs {
1095 llargs.push(unpack_result!(bcx, {
1096 trans_arg_datum(bcx, arg_tys[1], rhs,
1097 arg_cleanup_scope,
1098 if autoref { DoAutorefArg(rhs_id) } else { DontAutorefArg })
1099 }));
1100 }
1101 }
1102 ArgVals(vs) => {
1103 llargs.push_all(vs);
1104 }
1105 }
1106
1107 bcx
1108 }
1109
1110 #[derive(Copy, Clone)]
1111 pub enum AutorefArg {
1112 DontAutorefArg,
1113 DoAutorefArg(ast::NodeId)
1114 }
1115
1116 pub fn trans_arg_datum<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1117 formal_arg_ty: Ty<'tcx>,
1118 arg_datum: Datum<'tcx, Expr>,
1119 arg_cleanup_scope: cleanup::ScopeId,
1120 autoref_arg: AutorefArg)
1121 -> Result<'blk, 'tcx> {
1122 let _icx = push_ctxt("trans_arg_datum");
1123 let mut bcx = bcx;
1124 let ccx = bcx.ccx();
1125
1126 debug!("trans_arg_datum({})",
1127 formal_arg_ty.repr(bcx.tcx()));
1128
1129 let arg_datum_ty = arg_datum.ty;
1130
1131 debug!(" arg datum: {}", arg_datum.to_string(bcx.ccx()));
1132
1133 let mut val;
1134 // FIXME(#3548) use the adjustments table
1135 match autoref_arg {
1136 DoAutorefArg(arg_id) => {
1137 // We will pass argument by reference
1138 // We want an lvalue, so that we can pass by reference and
1139 let arg_datum = unpack_datum!(
1140 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
1141 val = arg_datum.val;
1142 }
1143 DontAutorefArg => {
1144 // Make this an rvalue, since we are going to be
1145 // passing ownership.
1146 let arg_datum = unpack_datum!(
1147 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
1148
1149 // Now that arg_datum is owned, get it into the appropriate
1150 // mode (ref vs value).
1151 let arg_datum = unpack_datum!(
1152 bcx, arg_datum.to_appropriate_datum(bcx));
1153
1154 // Technically, ownership of val passes to the callee.
1155 // However, we must cleanup should we panic before the
1156 // callee is actually invoked.
1157 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
1158 }
1159 }
1160
1161 if formal_arg_ty != arg_datum_ty {
1162 // this could happen due to e.g. subtyping
1163 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
1164 debug!("casting actual type ({}) to match formal ({})",
1165 bcx.val_to_string(val), bcx.llty_str(llformal_arg_ty));
1166 debug!("Rust types: {}; {}", ty_to_string(bcx.tcx(), arg_datum_ty),
1167 ty_to_string(bcx.tcx(), formal_arg_ty));
1168 val = PointerCast(bcx, val, llformal_arg_ty);
1169 }
1170
1171 debug!("--- trans_arg_datum passing {}", bcx.val_to_string(val));
1172 Result::new(bcx, val)
1173 }