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 /*!
12 * Handles translation of callees as well as other call-related
13 * things. Callees are a superset of normal rust values and sometimes
14 * have different representations. In particular, top-level fn items
15 * and methods are represented as just a fn ptr and not a full
16 * closure.
17 */
18
19 use back::abi;
20 use driver::session;
21 use lib::llvm::{ValueRef, NoAliasAttribute, StructRetAttribute, NoCaptureAttribute};
22 use lib::llvm::llvm;
23 use metadata::csearch;
24 use middle::trans::base;
25 use middle::trans::base::*;
26 use middle::trans::build::*;
27 use middle::trans::callee;
28 use middle::trans::cleanup;
29 use middle::trans::cleanup::CleanupMethods;
30 use middle::trans::common;
31 use middle::trans::common::*;
32 use middle::trans::datum::*;
33 use middle::trans::datum::Datum;
34 use middle::trans::expr;
35 use middle::trans::glue;
36 use middle::trans::inline;
37 use middle::trans::meth;
38 use middle::trans::monomorphize;
39 use middle::trans::type_of;
40 use middle::trans::foreign;
41 use middle::ty;
42 use middle::subst::Subst;
43 use middle::typeck;
44 use middle::typeck::coherence::make_substs_for_receiver_types;
45 use middle::typeck::MethodCall;
46 use util::ppaux::Repr;
47
48 use middle::trans::type_::Type;
49
50 use syntax::ast;
51 use synabi = syntax::abi;
52 use syntax::ast_map;
53
54 pub struct MethodData {
55 pub llfn: ValueRef,
56 pub llself: ValueRef,
57 }
58
59 pub enum CalleeData {
60 Closure(Datum<Lvalue>),
61
62 // Represents a (possibly monomorphized) top-level fn item or method
63 // item. Note that this is just the fn-ptr and is not a Rust closure
64 // value (which is a pair).
65 Fn(/* llfn */ ValueRef),
66
67 TraitMethod(MethodData)
68 }
69
70 pub struct Callee<'a> {
71 pub bcx: &'a Block<'a>,
72 pub data: CalleeData
73 }
74
75 fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
76 let _icx = push_ctxt("trans_callee");
77 debug!("callee::trans(expr={})", expr.repr(bcx.tcx()));
78
79 // pick out special kinds of expressions that can be called:
80 match expr.node {
81 ast::ExprPath(_) => {
82 return trans_def(bcx, bcx.def(expr.id), expr);
83 }
84 _ => {}
85 }
86
87 // any other expressions are closures:
88 return datum_callee(bcx, expr);
89
90 fn datum_callee<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
91 let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
92 match ty::get(datum.ty).sty {
93 ty::ty_bare_fn(..) => {
94 let llval = datum.to_llscalarish(bcx);
95 return Callee {bcx: bcx, data: Fn(llval)};
96 }
97 ty::ty_closure(..) => {
98 let datum = unpack_datum!(
99 bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
100 return Callee {bcx: bcx, data: Closure(datum)};
101 }
102 _ => {
103 bcx.tcx().sess.span_bug(
104 expr.span,
105 format!("type of callee is neither bare-fn nor closure: {}",
106 bcx.ty_to_str(datum.ty)));
107 }
108 }
109 }
110
111 fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
112 return Callee {bcx: bcx, data: Fn(llfn)};
113 }
114
115 fn trans_def<'a>(bcx: &'a Block<'a>, def: ast::Def, ref_expr: &ast::Expr)
116 -> Callee<'a> {
117 match def {
118 ast::DefFn(did, _) |
119 ast::DefStaticMethod(did, ast::FromImpl(_), _) => {
120 fn_callee(bcx, trans_fn_ref(bcx, did, ExprId(ref_expr.id)))
121 }
122 ast::DefStaticMethod(impl_did,
123 ast::FromTrait(trait_did),
124 _) => {
125 fn_callee(bcx, meth::trans_static_method_callee(bcx, impl_did,
126 trait_did,
127 ref_expr.id))
128 }
129 ast::DefVariant(tid, vid, _) => {
130 // nullary variants are not callable
131 assert!(ty::enum_variant_with_id(bcx.tcx(),
132 tid,
133 vid).args.len() > 0u);
134 fn_callee(bcx, trans_fn_ref(bcx, vid, ExprId(ref_expr.id)))
135 }
136 ast::DefStruct(def_id) => {
137 fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
138 }
139 ast::DefStatic(..) |
140 ast::DefArg(..) |
141 ast::DefLocal(..) |
142 ast::DefBinding(..) |
143 ast::DefUpvar(..) => {
144 datum_callee(bcx, ref_expr)
145 }
146 ast::DefMod(..) | ast::DefForeignMod(..) | ast::DefTrait(..) |
147 ast::DefTy(..) | ast::DefPrimTy(..) |
148 ast::DefUse(..) | ast::DefTyParamBinder(..) |
149 ast::DefRegion(..) | ast::DefLabel(..) | ast::DefTyParam(..) |
150 ast::DefSelfTy(..) | ast::DefMethod(..) => {
151 bcx.tcx().sess.span_bug(
152 ref_expr.span,
153 format!("cannot translate def {:?} \
154 to a callable thing!", def));
155 }
156 }
157 }
158 }
159
160 pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
161 /*!
162 *
163 * Translates a reference (with id `ref_id`) to the fn/method
164 * with id `def_id` into a function pointer. This may require
165 * monomorphization or inlining. */
166
167 let _icx = push_ctxt("trans_fn_ref");
168
169 let type_params = node_id_type_params(bcx, node);
170 let vtable_key = match node {
171 ExprId(id) => MethodCall::expr(id),
172 MethodCall(method_call) => method_call
173 };
174 let vtables = node_vtables(bcx, vtable_key);
175 debug!("trans_fn_ref(def_id={}, node={:?}, type_params={}, vtables={})",
176 def_id.repr(bcx.tcx()), node, type_params.repr(bcx.tcx()),
177 vtables.repr(bcx.tcx()));
178 trans_fn_ref_with_vtables(bcx, def_id, node,
179 type_params,
180 vtables)
181 }
182
183 fn trans_fn_ref_with_vtables_to_callee<'a>(bcx: &'a Block<'a>,
184 def_id: ast::DefId,
185 ref_id: ast::NodeId,
186 type_params: Vec<ty::t>,
187 vtables: Option<typeck::vtable_res>)
188 -> Callee<'a> {
189 Callee {bcx: bcx,
190 data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ExprId(ref_id),
191 type_params, vtables))}
192 }
193
194 fn resolve_default_method_vtables(bcx: &Block,
195 impl_id: ast::DefId,
196 method: &ty::Method,
197 substs: &ty::substs,
198 impl_vtables: Option<typeck::vtable_res>)
199 -> (typeck::vtable_res, typeck::vtable_param_res) {
200
201 // Get the vtables that the impl implements the trait at
202 let impl_res = ty::lookup_impl_vtables(bcx.tcx(), impl_id);
203
204 // Build up a param_substs that we are going to resolve the
205 // trait_vtables under.
206 let param_substs = param_substs {
207 tys: substs.tps.clone(),
208 self_ty: substs.self_ty,
209 vtables: impl_vtables.clone(),
210 self_vtables: None
211 };
212
213 let mut param_vtables = resolve_vtables_under_param_substs(
214 bcx.tcx(), Some(¶m_substs), impl_res.trait_vtables.as_slice());
215
216 // Now we pull any vtables for parameters on the actual method.
217 let num_method_vtables = method.generics.type_param_defs().len();
218 match impl_vtables {
219 Some(ref vtables) => {
220 let num_impl_type_parameters =
221 vtables.len() - num_method_vtables;
222 param_vtables.push_all(vtables.tailn(num_impl_type_parameters))
223 },
224 None => {
225 param_vtables.extend(range(0, num_method_vtables).map(
226 |_| -> typeck::vtable_param_res {
227 Vec::new()
228 }
229 ))
230 }
231 }
232
233 let self_vtables = resolve_param_vtables_under_param_substs(
234 bcx.tcx(), Some(¶m_substs), impl_res.self_vtables.as_slice());
235
236 (param_vtables, self_vtables)
237 }
238
239
240 pub fn trans_fn_ref_with_vtables(
241 bcx: &Block, //
242 def_id: ast::DefId, // def id of fn
243 node: ExprOrMethodCall, // node id of use of fn; may be zero if N/A
244 type_params: Vec<ty::t>, // values for fn's ty params
245 vtables: Option<typeck::vtable_res>) // vtables for the call
246 -> ValueRef {
247 /*!
248 * Translates a reference to a fn/method item, monomorphizing and
249 * inlining as it goes.
250 *
251 * # Parameters
252 *
253 * - `bcx`: the current block where the reference to the fn occurs
254 * - `def_id`: def id of the fn or method item being referenced
255 * - `node`: node id of the reference to the fn/method, if applicable.
256 * This parameter may be zero; but, if so, the resulting value may not
257 * have the right type, so it must be cast before being used.
258 * - `type_params`: values for each of the fn/method's type parameters
259 * - `vtables`: values for each bound on each of the type parameters
260 */
261
262 let _icx = push_ctxt("trans_fn_ref_with_vtables");
263 let ccx = bcx.ccx();
264 let tcx = bcx.tcx();
265
266 debug!("trans_fn_ref_with_vtables(bcx={}, def_id={}, node={:?}, \
267 type_params={}, vtables={})",
268 bcx.to_str(),
269 def_id.repr(tcx),
270 node,
271 type_params.repr(tcx),
272 vtables.repr(tcx));
273
274 assert!(type_params.iter().all(|t| !ty::type_needs_infer(*t)));
275
276 // Polytype of the function item (may have type params)
277 let fn_tpt = ty::lookup_item_type(tcx, def_id);
278
279 let substs = ty::substs {
280 regions: ty::ErasedRegions,
281 self_ty: None,
282 tps: type_params
283 };
284
285 // Load the info for the appropriate trait if necessary.
286 match ty::trait_of_method(tcx, def_id) {
287 None => {}
288 Some(trait_id) => {
289 ty::populate_implementations_for_trait_if_necessary(tcx, trait_id)
290 }
291 }
292
293 // We need to do a bunch of special handling for default methods.
294 // We need to modify the def_id and our substs in order to monomorphize
295 // the function.
296 let (is_default, def_id, substs, self_vtables, vtables) =
297 match ty::provided_source(tcx, def_id) {
298 None => (false, def_id, substs, None, vtables),
299 Some(source_id) => {
300 // There are two relevant substitutions when compiling
301 // default methods. First, there is the substitution for
302 // the type parameters of the impl we are using and the
303 // method we are calling. This substitution is the substs
304 // argument we already have.
305 // In order to compile a default method, though, we need
306 // to consider another substitution: the substitution for
307 // the type parameters on trait; the impl we are using
308 // implements the trait at some particular type
309 // parameters, and we need to substitute for those first.
310 // So, what we need to do is find this substitution and
311 // compose it with the one we already have.
312
313 let impl_id = ty::method(tcx, def_id).container_id();
314 let method = ty::method(tcx, source_id);
315 let trait_ref = ty::impl_trait_ref(tcx, impl_id)
316 .expect("could not find trait_ref for impl with \
317 default methods");
318
319 // Compute the first substitution
320 let first_subst = make_substs_for_receiver_types(
321 tcx, impl_id, &*trait_ref, &*method);
322
323 // And compose them
324 let new_substs = first_subst.subst(tcx, &substs);
325
326 debug!("trans_fn_with_vtables - default method: \
327 substs = {}, trait_subst = {}, \
328 first_subst = {}, new_subst = {}, \
329 vtables = {}",
330 substs.repr(tcx), trait_ref.substs.repr(tcx),
331 first_subst.repr(tcx), new_substs.repr(tcx),
332 vtables.repr(tcx));
333
334 let (param_vtables, self_vtables) =
335 resolve_default_method_vtables(bcx, impl_id,
336 &*method, &substs, vtables);
337
338 debug!("trans_fn_with_vtables - default method: \
339 self_vtable = {}, param_vtables = {}",
340 self_vtables.repr(tcx), param_vtables.repr(tcx));
341
342 (true, source_id,
343 new_substs, Some(self_vtables), Some(param_vtables))
344 }
345 };
346
347 // Check whether this fn has an inlined copy and, if so, redirect
348 // def_id to the local id of the inlined copy.
349 let def_id = {
350 if def_id.krate != ast::LOCAL_CRATE {
351 inline::maybe_instantiate_inline(ccx, def_id)
352 } else {
353 def_id
354 }
355 };
356
357 // We must monomorphise if the fn has type parameters, is a rust
358 // intrinsic, or is a default method. In particular, if we see an
359 // intrinsic that is inlined from a different crate, we want to reemit the
360 // intrinsic instead of trying to call it in the other crate.
361 let must_monomorphise = if substs.tps.len() > 0 || is_default {
362 true
363 } else if def_id.krate == ast::LOCAL_CRATE {
364 let map_node = session::expect(
365 ccx.sess(),
366 tcx.map.find(def_id.node),
367 || "local item should be in ast map".to_strbuf());
368
369 match map_node {
370 ast_map::NodeForeignItem(_) => {
371 tcx.map.get_foreign_abi(def_id.node) == synabi::RustIntrinsic
372 }
373 _ => false
374 }
375 } else {
376 false
377 };
378
379 // Create a monomorphic version of generic functions
380 if must_monomorphise {
381 // Should be either intra-crate or inlined.
382 assert_eq!(def_id.krate, ast::LOCAL_CRATE);
383
384 let opt_ref_id = match node {
385 ExprId(id) => if id != 0 { Some(id) } else { None },
386 MethodCall(_) => None,
387 };
388
389 let (val, must_cast) =
390 monomorphize::monomorphic_fn(ccx, def_id, &substs,
391 vtables, self_vtables,
392 opt_ref_id);
393 let mut val = val;
394 if must_cast && node != ExprId(0) {
395 // Monotype of the REFERENCE to the function (type params
396 // are subst'd)
397 let ref_ty = match node {
398 ExprId(id) => node_id_type(bcx, id),
399 MethodCall(method_call) => {
400 let t = bcx.tcx().method_map.borrow().get(&method_call).ty;
401 monomorphize_type(bcx, t)
402 }
403 };
404
405 val = PointerCast(
406 bcx, val, type_of::type_of_fn_from_ty(ccx, ref_ty).ptr_to());
407 }
408 return val;
409 }
410
411 // Find the actual function pointer.
412 let mut val = {
413 if def_id.krate == ast::LOCAL_CRATE {
414 // Internal reference.
415 get_item_val(ccx, def_id.node)
416 } else {
417 // External reference.
418 trans_external_path(ccx, def_id, fn_tpt.ty)
419 }
420 };
421
422 // This is subtle and surprising, but sometimes we have to bitcast
423 // the resulting fn pointer. The reason has to do with external
424 // functions. If you have two crates that both bind the same C
425 // library, they may not use precisely the same types: for
426 // example, they will probably each declare their own structs,
427 // which are distinct types from LLVM's point of view (nominal
428 // types).
429 //
430 // Now, if those two crates are linked into an application, and
431 // they contain inlined code, you can wind up with a situation
432 // where both of those functions wind up being loaded into this
433 // application simultaneously. In that case, the same function
434 // (from LLVM's point of view) requires two types. But of course
435 // LLVM won't allow one function to have two types.
436 //
437 // What we currently do, therefore, is declare the function with
438 // one of the two types (whichever happens to come first) and then
439 // bitcast as needed when the function is referenced to make sure
440 // it has the type we expect.
441 //
442 // This can occur on either a crate-local or crate-external
443 // reference. It also occurs when testing libcore and in some
444 // other weird situations. Annoying.
445 let llty = type_of::type_of_fn_from_ty(ccx, fn_tpt.ty);
446 let llptrty = llty.ptr_to();
447 if val_ty(val) != llptrty {
448 val = BitCast(bcx, val, llptrty);
449 }
450
451 val
452 }
453
454 // ______________________________________________________________________
455 // Translating calls
456
457 pub fn trans_call<'a>(
458 in_cx: &'a Block<'a>,
459 call_ex: &ast::Expr,
460 f: &ast::Expr,
461 args: CallArgs,
462 dest: expr::Dest)
463 -> &'a Block<'a> {
464 let _icx = push_ctxt("trans_call");
465 trans_call_inner(in_cx,
466 Some(common::expr_info(call_ex)),
467 expr_ty(in_cx, f),
468 |cx, _| trans(cx, f),
469 args,
470 Some(dest)).bcx
471 }
472
473 pub fn trans_method_call<'a>(
474 bcx: &'a Block<'a>,
475 call_ex: &ast::Expr,
476 rcvr: &ast::Expr,
477 args: CallArgs,
478 dest: expr::Dest)
479 -> &'a Block<'a> {
480 let _icx = push_ctxt("trans_method_call");
481 debug!("trans_method_call(call_ex={})", call_ex.repr(bcx.tcx()));
482 let method_call = MethodCall::expr(call_ex.id);
483 let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
484 trans_call_inner(
485 bcx,
486 Some(common::expr_info(call_ex)),
487 monomorphize_type(bcx, method_ty),
488 |cx, arg_cleanup_scope| {
489 meth::trans_method_callee(cx, method_call, Some(rcvr), arg_cleanup_scope)
490 },
491 args,
492 Some(dest)).bcx
493 }
494
495 pub fn trans_lang_call<'a>(
496 bcx: &'a Block<'a>,
497 did: ast::DefId,
498 args: &[ValueRef],
499 dest: Option<expr::Dest>)
500 -> Result<'a> {
501 let fty = if did.krate == ast::LOCAL_CRATE {
502 ty::node_id_to_type(bcx.tcx(), did.node)
503 } else {
504 csearch::get_type(bcx.tcx(), did).ty
505 };
506 callee::trans_call_inner(bcx,
507 None,
508 fty,
509 |bcx, _| {
510 trans_fn_ref_with_vtables_to_callee(bcx,
511 did,
512 0,
513 vec!(),
514 None)
515 },
516 ArgVals(args),
517 dest)
518 }
519
520 pub fn trans_call_inner<'a>(
521 bcx: &'a Block<'a>,
522 call_info: Option<NodeInfo>,
523 callee_ty: ty::t,
524 get_callee: |bcx: &'a Block<'a>,
525 arg_cleanup_scope: cleanup::ScopeId|
526 -> Callee<'a>,
527 args: CallArgs,
528 dest: Option<expr::Dest>)
529 -> Result<'a> {
530 /*!
531 * This behemoth of a function translates function calls.
532 * Unfortunately, in order to generate more efficient LLVM
533 * output at -O0, it has quite a complex signature (refactoring
534 * this into two functions seems like a good idea).
535 *
536 * In particular, for lang items, it is invoked with a dest of
537 * None, and in that case the return value contains the result of
538 * the fn. The lang item must not return a structural type or else
539 * all heck breaks loose.
540 *
541 * For non-lang items, `dest` is always Some, and hence the result
542 * is written into memory somewhere. Nonetheless we return the
543 * actual return value of the function.
544 */
545
546 // Introduce a temporary cleanup scope that will contain cleanups
547 // for the arguments while they are being evaluated. The purpose
548 // this cleanup is to ensure that, should a failure occur while
549 // evaluating argument N, the values for arguments 0...N-1 are all
550 // cleaned up. If no failure occurs, the values are handed off to
551 // the callee, and hence none of the cleanups in this temporary
552 // scope will ever execute.
553 let fcx = bcx.fcx;
554 let ccx = fcx.ccx;
555 let arg_cleanup_scope = fcx.push_custom_cleanup_scope();
556
557 let callee = get_callee(bcx, cleanup::CustomScope(arg_cleanup_scope));
558 let mut bcx = callee.bcx;
559
560 let (llfn, llenv, llself) = match callee.data {
561 Fn(llfn) => {
562 (llfn, None, None)
563 }
564 TraitMethod(d) => {
565 (d.llfn, None, Some(d.llself))
566 }
567 Closure(d) => {
568 // Closures are represented as (llfn, llclosure) pair:
569 // load the requisite values out.
570 let pair = d.to_llref();
571 let llfn = GEPi(bcx, pair, [0u, abi::fn_field_code]);
572 let llfn = Load(bcx, llfn);
573 let llenv = GEPi(bcx, pair, [0u, abi::fn_field_box]);
574 let llenv = Load(bcx, llenv);
575 (llfn, Some(llenv), None)
576 }
577 };
578
579 let (abi, ret_ty) = match ty::get(callee_ty).sty {
580 ty::ty_bare_fn(ref f) => (f.abi, f.sig.output),
581 ty::ty_closure(ref f) => (synabi::Rust, f.sig.output),
582 _ => fail!("expected bare rust fn or closure in trans_call_inner")
583 };
584 let is_rust_fn = abi == synabi::Rust || abi == synabi::RustIntrinsic;
585
586 // Generate a location to store the result. If the user does
587 // not care about the result, just make a stack slot.
588 let opt_llretslot = match dest {
589 None => {
590 assert!(!type_of::return_uses_outptr(ccx, ret_ty));
591 None
592 }
593 Some(expr::SaveIn(dst)) => Some(dst),
594 Some(expr::Ignore) => {
595 if !type_is_zero_size(ccx, ret_ty) {
596 Some(alloc_ty(bcx, ret_ty, "__llret"))
597 } else {
598 let llty = type_of::type_of(ccx, ret_ty);
599 Some(C_undef(llty.ptr_to()))
600 }
601 }
602 };
603
604 let mut llresult = unsafe {
605 llvm::LLVMGetUndef(Type::nil(ccx).ptr_to().to_ref())
606 };
607
608 // The code below invokes the function, using either the Rust
609 // conventions (if it is a rust fn) or the native conventions
610 // (otherwise). The important part is that, when all is sad
611 // and done, either the return value of the function will have been
612 // written in opt_llretslot (if it is Some) or `llresult` will be
613 // set appropriately (otherwise).
614 if is_rust_fn {
615 let mut llargs = Vec::new();
616
617 // Push the out-pointer if we use an out-pointer for this
618 // return type, otherwise push "undef".
619 if type_of::return_uses_outptr(ccx, ret_ty) {
620 llargs.push(opt_llretslot.unwrap());
621 }
622
623 // start at 1, because index 0 is the return value of the llvm func
624 let mut first_arg_offset = 1;
625
626 // Push the environment (or a trait object's self).
627 match (llenv, llself) {
628 (Some(llenv), None) => {
629 first_arg_offset += 1;
630 llargs.push(llenv)
631 },
632 (None, Some(llself)) => llargs.push(llself),
633 _ => {}
634 }
635
636 // Push the arguments.
637 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
638 cleanup::CustomScope(arg_cleanup_scope),
639 llself.is_some());
640
641 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
642
643 // A function pointer is called without the declaration
644 // available, so we have to apply any attributes with ABI
645 // implications directly to the call instruction. Right now,
646 // the only attribute we need to worry about is `sret`.
647 let mut attrs = Vec::new();
648 if type_of::return_uses_outptr(ccx, ret_ty) {
649 attrs.push((1, StructRetAttribute));
650 // The outptr can be noalias and nocapture because it's entirely
651 // invisible to the program.
652 attrs.push((1, NoAliasAttribute));
653 attrs.push((1, NoCaptureAttribute));
654 first_arg_offset += 1;
655 }
656
657 // The `noalias` attribute on the return value is useful to a
658 // function ptr caller.
659 match ty::get(ret_ty).sty {
660 // `~` pointer return values never alias because ownership
661 // is transferred
662 ty::ty_uniq(ty) => match ty::get(ty).sty {
663 ty::ty_str => {}
664 _ => attrs.push((0, NoAliasAttribute)),
665 },
666 _ => {}
667 }
668
669 debug!("trans_callee_inner: first_arg_offset={}", first_arg_offset);
670
671 for (idx, &t) in ty::ty_fn_args(callee_ty).iter().enumerate()
672 .map(|(i, v)| (i+first_arg_offset, v)) {
673 use middle::ty::{BrAnon, ReLateBound};
674 if !type_is_immediate(ccx, t) {
675 // if it's not immediate, we have a program-invisible pointer,
676 // which it can't possibly capture
677 attrs.push((idx, NoCaptureAttribute));
678 debug!("trans_callee_inner: argument {} nocapture because it's non-immediate", idx);
679 continue;
680 }
681
682 let t_ = ty::get(t);
683 match t_.sty {
684 ty::ty_rptr(ReLateBound(_, BrAnon(_)), _) => {
685 debug!("trans_callee_inner: argument {} nocapture because \
686 of anonymous lifetime", idx);
687 attrs.push((idx, NoCaptureAttribute));
688 },
689 _ => { }
690 }
691 }
692
693 // Invoke the actual rust fn and update bcx/llresult.
694 let (llret, b) = base::invoke(bcx,
695 llfn,
696 llargs,
697 attrs.as_slice(),
698 call_info);
699 bcx = b;
700 llresult = llret;
701
702 // If the Rust convention for this type is return via
703 // the return value, copy it into llretslot.
704 match opt_llretslot {
705 Some(llretslot) => {
706 if !type_of::return_uses_outptr(bcx.ccx(), ret_ty) &&
707 !type_is_zero_size(bcx.ccx(), ret_ty)
708 {
709 Store(bcx, llret, llretslot);
710 }
711 }
712 None => {}
713 }
714 } else {
715 // Lang items are the only case where dest is None, and
716 // they are always Rust fns.
717 assert!(dest.is_some());
718
719 let mut llargs = Vec::new();
720 let arg_tys = match args {
721 ArgExprs(a) => a.iter().map(|x| expr_ty(bcx, *x)).collect(),
722 _ => fail!("expected arg exprs.")
723 };
724 bcx = trans_args(bcx, args, callee_ty, &mut llargs,
725 cleanup::CustomScope(arg_cleanup_scope), false);
726 fcx.pop_custom_cleanup_scope(arg_cleanup_scope);
727 bcx = foreign::trans_native_call(bcx, callee_ty,
728 llfn, opt_llretslot.unwrap(),
729 llargs.as_slice(), arg_tys);
730 }
731
732 // If the caller doesn't care about the result of this fn call,
733 // drop the temporary slot we made.
734 match dest {
735 None => {
736 assert!(!type_of::return_uses_outptr(bcx.ccx(), ret_ty));
737 }
738 Some(expr::Ignore) => {
739 // drop the value if it is not being saved.
740 bcx = glue::drop_ty(bcx, opt_llretslot.unwrap(), ret_ty);
741 }
742 Some(expr::SaveIn(_)) => { }
743 }
744
745 if ty::type_is_bot(ret_ty) {
746 Unreachable(bcx);
747 }
748
749 Result::new(bcx, llresult)
750 }
751
752 pub enum CallArgs<'a> {
753 // Supply value of arguments as a list of expressions that must be
754 // translated. This is used in the common case of `foo(bar, qux)`.
755 ArgExprs(&'a [@ast::Expr]),
756
757 // Supply value of arguments as a list of LLVM value refs; frequently
758 // used with lang items and so forth, when the argument is an internal
759 // value.
760 ArgVals(&'a [ValueRef]),
761
762 // For overloaded operators: `(lhs, Option(rhs, rhs_id))`. `lhs`
763 // is the left-hand-side and `rhs/rhs_id` is the datum/expr-id of
764 // the right-hand-side (if any).
765 ArgOverloadedOp(Datum<Expr>, Option<(Datum<Expr>, ast::NodeId)>),
766 }
767
768 fn trans_args<'a>(cx: &'a Block<'a>,
769 args: CallArgs,
770 fn_ty: ty::t,
771 llargs: &mut Vec<ValueRef> ,
772 arg_cleanup_scope: cleanup::ScopeId,
773 ignore_self: bool)
774 -> &'a Block<'a> {
775 let _icx = push_ctxt("trans_args");
776 let arg_tys = ty::ty_fn_args(fn_ty);
777 let variadic = ty::fn_is_variadic(fn_ty);
778
779 let mut bcx = cx;
780
781 // First we figure out the caller's view of the types of the arguments.
782 // This will be needed if this is a generic call, because the callee has
783 // to cast her view of the arguments to the caller's view.
784 match args {
785 ArgExprs(arg_exprs) => {
786 let num_formal_args = arg_tys.len();
787 for (i, &arg_expr) in arg_exprs.iter().enumerate() {
788 if i == 0 && ignore_self {
789 continue;
790 }
791 let arg_ty = if i >= num_formal_args {
792 assert!(variadic);
793 expr_ty_adjusted(cx, arg_expr)
794 } else {
795 *arg_tys.get(i)
796 };
797
798 let arg_datum = unpack_datum!(bcx, expr::trans(bcx, arg_expr));
799 llargs.push(unpack_result!(bcx, {
800 trans_arg_datum(bcx, arg_ty, arg_datum,
801 arg_cleanup_scope,
802 DontAutorefArg)
803 }));
804 }
805 }
806 ArgOverloadedOp(lhs, rhs) => {
807 assert!(!variadic);
808
809 llargs.push(unpack_result!(bcx, {
810 trans_arg_datum(bcx, *arg_tys.get(0), lhs,
811 arg_cleanup_scope,
812 DontAutorefArg)
813 }));
814
815 match rhs {
816 Some((rhs, rhs_id)) => {
817 assert_eq!(arg_tys.len(), 2);
818
819 llargs.push(unpack_result!(bcx, {
820 trans_arg_datum(bcx, *arg_tys.get(1), rhs,
821 arg_cleanup_scope,
822 DoAutorefArg(rhs_id))
823 }));
824 }
825 None => assert_eq!(arg_tys.len(), 1)
826 }
827 }
828 ArgVals(vs) => {
829 llargs.push_all(vs);
830 }
831 }
832
833 bcx
834 }
835
836 pub enum AutorefArg {
837 DontAutorefArg,
838 DoAutorefArg(ast::NodeId)
839 }
840
841 pub fn trans_arg_datum<'a>(
842 bcx: &'a Block<'a>,
843 formal_arg_ty: ty::t,
844 arg_datum: Datum<Expr>,
845 arg_cleanup_scope: cleanup::ScopeId,
846 autoref_arg: AutorefArg)
847 -> Result<'a> {
848 let _icx = push_ctxt("trans_arg_datum");
849 let mut bcx = bcx;
850 let ccx = bcx.ccx();
851
852 debug!("trans_arg_datum({})",
853 formal_arg_ty.repr(bcx.tcx()));
854
855 let arg_datum_ty = arg_datum.ty;
856
857 debug!(" arg datum: {}", arg_datum.to_str(bcx.ccx()));
858
859 let mut val;
860 if ty::type_is_bot(arg_datum_ty) {
861 // For values of type _|_, we generate an
862 // "undef" value, as such a value should never
863 // be inspected. It's important for the value
864 // to have type lldestty (the callee's expected type).
865 let llformal_arg_ty = type_of::type_of(ccx, formal_arg_ty);
866 unsafe {
867 val = llvm::LLVMGetUndef(llformal_arg_ty.to_ref());
868 }
869 } else {
870 // FIXME(#3548) use the adjustments table
871 match autoref_arg {
872 DoAutorefArg(arg_id) => {
873 // We will pass argument by reference
874 // We want an lvalue, so that we can pass by reference and
875 let arg_datum = unpack_datum!(
876 bcx, arg_datum.to_lvalue_datum(bcx, "arg", arg_id));
877 val = arg_datum.val;
878 }
879 DontAutorefArg => {
880 // Make this an rvalue, since we are going to be
881 // passing ownership.
882 let arg_datum = unpack_datum!(
883 bcx, arg_datum.to_rvalue_datum(bcx, "arg"));
884
885 // Now that arg_datum is owned, get it into the appropriate
886 // mode (ref vs value).
887 let arg_datum = unpack_datum!(
888 bcx, arg_datum.to_appropriate_datum(bcx));
889
890 // Technically, ownership of val passes to the callee.
891 // However, we must cleanup should we fail before the
892 // callee is actually invoked.
893 val = arg_datum.add_clean(bcx.fcx, arg_cleanup_scope);
894 }
895 }
896
897 if formal_arg_ty != arg_datum_ty {
898 // this could happen due to e.g. subtyping
899 let llformal_arg_ty = type_of::type_of_explicit_arg(ccx, formal_arg_ty);
900 debug!("casting actual type ({}) to match formal ({})",
901 bcx.val_to_str(val), bcx.llty_str(llformal_arg_ty));
902 val = PointerCast(bcx, val, llformal_arg_ty);
903 }
904 }
905
906 debug!("--- trans_arg_datum passing {}", bcx.val_to_str(val));
907 Result::new(bcx, val)
908 }
librustc/middle/trans/callee.rs:519:1-519:1 -fn- definition:
pub fn trans_call_inner<'a>(
bcx: &'a Block<'a>,
call_info: Option<NodeInfo>,
references:- 5505: };
506: callee::trans_call_inner(bcx,
507: None,
librustc/middle/trans/expr.rs:
1444: let method_ty = bcx.tcx().method_map.borrow().get(&method_call).ty;
1445: callee::trans_call_inner(bcx,
1446: Some(expr_info(expr)),
librustc/middle/trans/reflect.rs:
101: }
102: let result = unpack_result!(bcx, callee::trans_call_inner(
103: self.bcx, None, mth_ty,
librustc/middle/trans/callee.rs:
464: let _icx = push_ctxt("trans_call");
465: trans_call_inner(in_cx,
466: Some(common::expr_info(call_ex)),
librustc/middle/trans/callee.rs:111:4-111:4 -fn- definition:
fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
return Callee {bcx: bcx, data: Fn(llfn)};
}
references:- 4133: vid).args.len() > 0u);
134: fn_callee(bcx, trans_fn_ref(bcx, vid, ExprId(ref_expr.id)))
135: }
136: ast::DefStruct(def_id) => {
137: fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
138: }
librustc/middle/trans/callee.rs:767:1-767:1 -fn- definition:
fn trans_args<'a>(cx: &'a Block<'a>,
args: CallArgs,
fn_ty: ty::t,
references:- 2723: };
724: bcx = trans_args(bcx, args, callee_ty, &mut llargs,
725: cleanup::CustomScope(arg_cleanup_scope), false);
librustc/middle/trans/callee.rs:90:4-90:4 -fn- definition:
fn datum_callee<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
let DatumBlock {bcx: mut bcx, datum} = expr::trans(bcx, expr);
match ty::get(datum.ty).sty {
references:- 287: // any other expressions are closures:
88: return datum_callee(bcx, expr);
--
143: ast::DefUpvar(..) => {
144: datum_callee(bcx, ref_expr)
145: }
librustc/middle/trans/callee.rs:53:1-53:1 -struct- definition:
pub struct MethodData {
pub llfn: ValueRef,
pub llself: ValueRef,
references:- 2librustc/middle/trans/meth.rs:
422: bcx: bcx,
423: data: TraitMethod(MethodData {
424: llfn: mptr,
librustc/middle/trans/callee.rs:
67: TraitMethod(MethodData)
68: }
librustc/middle/trans/callee.rs:239:1-239:1 -fn- definition:
pub fn trans_fn_ref_with_vtables(
bcx: &Block, //
def_id: ast::DefId, // def id of fn
references:- 5189: Callee {bcx: bcx,
190: data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ExprId(ref_id),
191: type_params, vtables))}
librustc/middle/trans/meth.rs:
262: // translate the function
263: let llfn = trans_fn_ref_with_vtables(bcx,
264: mth_id,
--
517: } else {
518: trans_fn_ref_with_vtables(bcx, m_id, ExprId(0),
519: substs.clone(), Some(vtables.clone()))
librustc/middle/trans/callee.rs:751:1-751:1 -enum- definition:
pub enum CallArgs<'a> {
// Supply value of arguments as a list of expressions that must be
// translated. This is used in the common case of `foo(bar, qux)`.
references:- 4526: -> Callee<'a>,
527: args: CallArgs,
528: dest: Option<expr::Dest>)
--
768: fn trans_args<'a>(cx: &'a Block<'a>,
769: args: CallArgs,
770: fn_ty: ty::t,
librustc/middle/trans/callee.rs:840:1-840:1 -fn- definition:
pub fn trans_arg_datum<'a>(
bcx: &'a Block<'a>,
formal_arg_ty: ty::t,
references:- 4809: llargs.push(unpack_result!(bcx, {
810: trans_arg_datum(bcx, *arg_tys.get(0), lhs,
811: arg_cleanup_scope,
--
819: llargs.push(unpack_result!(bcx, {
820: trans_arg_datum(bcx, *arg_tys.get(1), rhs,
821: arg_cleanup_scope,
librustc/middle/trans/asm.rs:
54: unpack_result!(bcx, {
55: callee::trans_arg_datum(bcx,
56: expr_ty(bcx, input),
librustc/middle/trans/callee.rs:494:1-494:1 -fn- definition:
pub fn trans_lang_call<'a>(
bcx: &'a Block<'a>,
did: ast::DefId,
references:- 9librustc/middle/trans/base.rs:
380: let drop_glue = glue::get_drop_glue(ccx, t);
381: let r = callee::trans_lang_call(
382: bcx,
librustc/middle/trans/_match.rs:
1234: StrEqFnLangItem);
1235: let result = callee::trans_lang_call(cx, did, [lhs, rhs], None);
1236: Result {
--
1257: UniqStrEqFnLangItem);
1258: let result = callee::trans_lang_call(cx, did, [scratch_lhs, scratch_rhs], None);
1259: Result {
librustc/middle/trans/tvec.rs:
254: StrDupUniqFnLangItem);
255: let bcx = callee::trans_lang_call(
256: bcx,
librustc/middle/trans/controlflow.rs:
357: let did = langcall(bcx, Some(sp), "", FailFnLangItem);
358: let bcx = callee::trans_lang_call(bcx,
359: did,
--
375: let did = langcall(bcx, Some(sp), "", FailBoundsCheckFnLangItem);
376: let bcx = callee::trans_lang_call(bcx,
377: did,
librustc/middle/trans/glue.rs:
55: let _icx = push_ctxt("trans_exchange_free");
56: callee::trans_lang_call(cx,
57: langcall(cx, None, "", ExchangeFreeFnLangItem),
librustc/middle/trans/callee.rs:69:1-69:1 -struct- definition:
pub struct Callee<'a> {
pub bcx: &'a Block<'a>,
pub data: CalleeData
references:- 1799: bcx, datum.to_lvalue_datum(bcx, "callee", expr.id));
100: return Callee {bcx: bcx, data: Closure(datum)};
101: }
--
111: fn fn_callee<'a>(bcx: &'a Block<'a>, llfn: ValueRef) -> Callee<'a> {
112: return Callee {bcx: bcx, data: Fn(llfn)};
113: }
--
188: -> Callee<'a> {
189: Callee {bcx: bcx,
190: data: Fn(trans_fn_ref_with_vtables(bcx, def_id, ExprId(ref_id),
librustc/middle/trans/meth.rs:
100: typeck::MethodStatic(did) => {
101: Callee {
102: bcx: bcx,
--
421: return Callee {
422: bcx: bcx,
librustc/middle/trans/callee.rs:
75: fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
76: let _icx = push_ctxt("trans_callee");
--
115: fn trans_def<'a>(bcx: &'a Block<'a>, def: ast::Def, ref_expr: &ast::Expr)
116: -> Callee<'a> {
117: match def {
--
187: vtables: Option<typeck::vtable_res>)
188: -> Callee<'a> {
189: Callee {bcx: bcx,
librustc/middle/trans/meth.rs:
82: arg_cleanup_scope: cleanup::ScopeId)
83: -> Callee<'a> {
84: let _icx = push_ctxt("meth::trans_method_callee");
--
386: llpair: ValueRef)
387: -> Callee<'a> {
388: /*!
librustc/middle/trans/callee.rs:
525: arg_cleanup_scope: cleanup::ScopeId|
526: -> Callee<'a>,
527: args: CallArgs,
librustc/middle/trans/callee.rs:159:1-159:1 -fn- definition:
pub fn trans_fn_ref(bcx: &Block, def_id: ast::DefId, node: ExprOrMethodCall) -> ValueRef {
/*!
*
references:- 7133: vid).args.len() > 0u);
134: fn_callee(bcx, trans_fn_ref(bcx, vid, ExprId(ref_expr.id)))
135: }
136: ast::DefStruct(def_id) => {
137: fn_callee(bcx, trans_fn_ref(bcx, def_id, ExprId(ref_expr.id)))
138: }
librustc/middle/trans/expr.rs:
831: ast::DefStaticMethod(did, ast::FromImpl(_), _) => {
832: callee::trans_fn_ref(bcx, did, ExprId(ref_expr.id))
833: }
librustc/middle/trans/meth.rs:
102: bcx: bcx,
103: data: Fn(callee::trans_fn_ref(bcx, did, MethodCall(method_call)))
104: }
librustc/middle/trans/cleanup.rs:
666: let def_id = common::langcall(pad_bcx, None, "", EhPersonalityLangItem);
667: let llpersonality = callee::trans_fn_ref(pad_bcx, def_id, ExprId(0));
librustc/middle/trans/expr.rs:
791: // N-ary variant.
792: let llfn = callee::trans_fn_ref(bcx, vid, ExprId(ref_expr.id));
793: Store(bcx, llfn, lldest);