1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 use llvm::{ValueRef, CallConv, get_param};
15 use middle::weak_lang_items;
16 use trans::base::{llvm_linkage_by_name, push_ctxt};
22 use trans::monomorphize;
23 use trans::type_::Type;
24 use trans::type_of::*;
26 use middle::ty::{self, Ty};
27 use middle::subst::Substs;
29 use std::ffi::CString;
32 use syntax::abi::{Cdecl, Aapcs, C, Win64, Abi};
33 use syntax::abi::{RustIntrinsic, Rust, RustCall, Stdcall, Fastcall, System};
34 use syntax::codemap::Span;
35 use syntax::parse::token::{InternedString, special_idents};
36 use syntax::parse::token;
38 use syntax::{attr, ast_map};
39 use syntax::print::pprust;
40 use util::ppaux::Repr;
42 ///////////////////////////////////////////////////////////////////////////
45 struct ForeignTypes<'tcx> {
46 /// Rust signature of the function
47 fn_sig: ty::FnSig<'tcx>,
49 /// Adapter object for handling native ABI rules (trust me, you
50 /// don't want to know)
53 /// LLVM types that will appear on the foreign function
57 struct LlvmSignature {
58 // LLVM versions of the types of this function's arguments.
59 llarg_tys: Vec<Type> ,
61 // LLVM version of the type that this function returns. Note that
62 // this *may not be* the declared return type of the foreign
63 // function, because the foreign function may opt to return via an
67 /// True if there is a return value (not bottom, not unit)
72 ///////////////////////////////////////////////////////////////////////////
73 // Calls to external functions
75 pub fn llvm_calling_convention(ccx: &CrateContext,
76 abi: Abi) -> CallConv {
77 match ccx.sess().target.target.adjust_abi(abi) {
79 // Intrinsics are emitted at the call site
80 ccx.sess().bug("asked to register intrinsic fn");
84 // FIXME(#3678) Implement linking to foreign fns with Rust ABI
85 ccx.sess().unimpl("foreign functions with Rust ABI");
89 // FIXME(#3678) Implement linking to foreign fns with Rust ABI
90 ccx.sess().unimpl("foreign functions with RustCall ABI");
93 // It's the ABI's job to select this, not us.
94 System => ccx.sess().bug("system abi should be selected elsewhere"),
96 Stdcall => llvm::X86StdcallCallConv,
97 Fastcall => llvm::X86FastcallCallConv,
99 Win64 => llvm::X86_64_Win64,
101 // These API constants ought to be more specific...
102 Cdecl => llvm::CCallConv,
103 Aapcs => llvm::CCallConv,
107 pub fn register_static(ccx: &CrateContext,
108 foreign_item: &ast::ForeignItem) -> ValueRef {
109 let ty = ty::node_id_to_type(ccx.tcx(), foreign_item.id);
110 let llty = type_of::type_of(ccx, ty);
112 let ident = link_name(foreign_item);
113 match attr::first_attr_value_str_by_name(&foreign_item.attrs[],
115 // If this is a static with a linkage specified, then we need to handle
116 // it a little specially. The typesystem prevents things like &T and
117 // extern "C" fn() from being non-null, so we can't just declare a
118 // static and call it a day. Some linkages (like weak) will make it such
119 // that the static actually has a null value.
121 let linkage = match llvm_linkage_by_name(name.get()) {
122 Some(linkage) => linkage,
124 ccx.sess().span_fatal(foreign_item.span,
125 "invalid linkage specified");
128 let llty2 = match ty.sty {
129 ty::ty_ptr(ref mt) => type_of::type_of(ccx, mt.ty),
131 ccx.sess().span_fatal(foreign_item.span,
132 "must have type `*T` or `*mut T`");
136 // Declare a symbol `foo` with the desired linkage.
137 let buf = CString::from_slice(ident.get().as_bytes());
138 let g1 = llvm::LLVMAddGlobal(ccx.llmod(), llty2.to_ref(),
140 llvm::SetLinkage(g1, linkage);
142 // Declare an internal global `extern_with_linkage_foo` which
143 // is initialized with the address of `foo`. If `foo` is
144 // discarded during linking (for example, if `foo` has weak
145 // linkage and there are no definitions), then
146 // `extern_with_linkage_foo` will instead be initialized to
148 let mut real_name = "_rust_extern_with_linkage_".to_string();
149 real_name.push_str(ident.get());
150 let real_name = CString::from_vec(real_name.into_bytes());
151 let g2 = llvm::LLVMAddGlobal(ccx.llmod(), llty.to_ref(),
153 llvm::SetLinkage(g2, llvm::InternalLinkage);
154 llvm::LLVMSetInitializer(g2, g1);
159 // Generate an external declaration.
160 let buf = CString::from_slice(ident.get().as_bytes());
161 llvm::LLVMAddGlobal(ccx.llmod(), llty.to_ref(), buf.as_ptr())
166 /// Registers a foreign function found in a library. Just adds a LLVM global.
167 pub fn register_foreign_item_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
168 abi: Abi, fty: Ty<'tcx>,
169 name: &str) -> ValueRef {
170 debug!("register_foreign_item_fn(abi={}, \
177 let cc = llvm_calling_convention(ccx, abi);
179 // Register the function as a C extern fn
180 let tys = foreign_types_for_fn_ty(ccx, fty);
182 // Make sure the calling convention is right for variadic functions
183 // (should've been caught if not in typeck)
184 if tys.fn_sig.variadic {
185 assert!(cc == llvm::CCallConv);
188 // Create the LLVM value for the C extern fn
189 let llfn_ty = lltype_for_fn_from_foreign_types(ccx, &tys);
191 let llfn = base::get_extern_fn(ccx,
192 &mut *ccx.externs().borrow_mut(),
197 add_argument_attributes(&tys, llfn);
202 /// Prepares a call to a native function. This requires adapting
203 /// from the Rust argument passing rules to the native rules.
207 /// - `callee_ty`: Rust type for the function we are calling
208 /// - `llfn`: the function pointer we are calling
209 /// - `llretptr`: where to store the return value of the function
210 /// - `llargs_rust`: a list of the argument values, prepared
211 /// as they would be if calling a Rust function
212 /// - `passed_arg_tys`: Rust type for the arguments. Normally we
213 /// can derive these from callee_ty but in the case of variadic
214 /// functions passed_arg_tys will include the Rust type of all
215 /// the arguments including the ones not specified in the fn's signature.
216 pub fn trans_native_call<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
220 llargs_rust: &[ValueRef],
221 passed_arg_tys: Vec<Ty<'tcx>>)
227 debug!("trans_native_call(callee_ty={}, \
231 ccx.tn().val_to_string(llfn),
232 ccx.tn().val_to_string(llretptr));
234 let (fn_abi, fn_sig) = match callee_ty.sty {
235 ty::ty_bare_fn(_, ref fn_ty) => (fn_ty.abi, &fn_ty.sig),
236 _ => ccx.sess().bug("trans_native_call called on non-function type")
238 let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);
239 let llsig = foreign_signature(ccx, &fn_sig, &passed_arg_tys[]);
240 let fn_type = cabi::compute_abi_info(ccx,
245 let arg_tys: &[cabi::ArgType] = &fn_type.arg_tys[];
247 let mut llargs_foreign = Vec::new();
249 // If the foreign ABI expects return value by pointer, supply the
250 // pointer that Rust gave us. Sometimes we have to bitcast
251 // because foreign fns return slightly different (but equivalent)
252 // views on the same type (e.g., i64 in place of {i32,i32}).
253 if fn_type.ret_ty.is_indirect() {
254 match fn_type.ret_ty.cast {
257 BitCast(bcx, llretptr, ty.ptr_to());
258 llargs_foreign.push(llcastedretptr);
261 llargs_foreign.push(llretptr);
266 for (i, &llarg_rust) in llargs_rust.iter().enumerate() {
267 let mut llarg_rust = llarg_rust;
269 if arg_tys[i].is_ignore() {
273 // Does Rust pass this argument by pointer?
274 let rust_indirect = type_of::arg_is_indirect(ccx, passed_arg_tys[i]);
276 debug!("argument {}, llarg_rust={}, rust_indirect={}, arg_ty={}",
278 ccx.tn().val_to_string(llarg_rust),
280 ccx.tn().type_to_string(arg_tys[i].ty));
282 // Ensure that we always have the Rust value indirectly,
283 // because it makes bitcasting easier.
287 type_of::type_of(ccx, passed_arg_tys[i]),
289 base::store_ty(bcx, llarg_rust, scratch, passed_arg_tys[i]);
290 llarg_rust = scratch;
293 debug!("llarg_rust={} (after indirection)",
294 ccx.tn().val_to_string(llarg_rust));
296 // Check whether we need to do any casting
297 match arg_tys[i].cast {
298 Some(ty) => llarg_rust = BitCast(bcx, llarg_rust, ty.ptr_to()),
302 debug!("llarg_rust={} (after casting)",
303 ccx.tn().val_to_string(llarg_rust));
305 // Finally, load the value if needed for the foreign ABI
306 let foreign_indirect = arg_tys[i].is_indirect();
307 let llarg_foreign = if foreign_indirect {
310 if ty::type_is_bool(passed_arg_tys[i]) {
311 let val = LoadRangeAssert(bcx, llarg_rust, 0, 2, llvm::False);
312 Trunc(bcx, val, Type::i1(bcx.ccx()))
314 Load(bcx, llarg_rust)
318 debug!("argument {}, llarg_foreign={}",
319 i, ccx.tn().val_to_string(llarg_foreign));
321 // fill padding with undef value
322 match arg_tys[i].pad {
323 Some(ty) => llargs_foreign.push(C_undef(ty)),
326 llargs_foreign.push(llarg_foreign);
329 let cc = llvm_calling_convention(ccx, fn_abi);
331 // A function pointer is called without the declaration available, so we have to apply
332 // any attributes with ABI implications directly to the call instruction.
333 let mut attrs = llvm::AttrBuilder::new();
335 // Add attributes that are always applicable, independent of the concrete foreign ABI
336 if fn_type.ret_ty.is_indirect() {
337 let llret_sz = machine::llsize_of_real(ccx, fn_type.ret_ty.ty);
339 // The outptr can be noalias and nocapture because it's entirely
340 // invisible to the program. We also know it's nonnull as well
341 // as how many bytes we can dereference
342 attrs.arg(1, llvm::NoAliasAttribute)
343 .arg(1, llvm::NoCaptureAttribute)
344 .arg(1, llvm::DereferenceableAttribute(llret_sz));
347 // Add attributes that depend on the concrete foreign ABI
348 let mut arg_idx = if fn_type.ret_ty.is_indirect() { 1 } else { 0 };
349 match fn_type.ret_ty.attr {
350 Some(attr) => { attrs.arg(arg_idx, attr); },
355 for arg_ty in &fn_type.arg_tys {
356 if arg_ty.is_ignore() {
360 if arg_ty.pad.is_some() { arg_idx += 1; }
362 if let Some(attr) = arg_ty.attr {
363 attrs.arg(arg_idx, attr);
369 let llforeign_retval = CallWithConv(bcx,
375 // If the function we just called does not use an outpointer,
376 // store the result into the rust outpointer. Cast the outpointer
377 // type to match because some ABIs will use a different type than
378 // the Rust type. e.g., a {u32,u32} struct could be returned as
380 if llsig.ret_def && !fn_type.ret_ty.is_indirect() {
381 let llrust_ret_ty = llsig.llret_ty;
382 let llforeign_ret_ty = match fn_type.ret_ty.cast {
384 None => fn_type.ret_ty.ty
387 debug!("llretptr={}", ccx.tn().val_to_string(llretptr));
388 debug!("llforeign_retval={}", ccx.tn().val_to_string(llforeign_retval));
389 debug!("llrust_ret_ty={}", ccx.tn().type_to_string(llrust_ret_ty));
390 debug!("llforeign_ret_ty={}", ccx.tn().type_to_string(llforeign_ret_ty));
392 if llrust_ret_ty == llforeign_ret_ty {
393 match fn_sig.output {
394 ty::FnConverging(result_ty) => {
395 base::store_ty(bcx, llforeign_retval, llretptr, result_ty)
397 ty::FnDiverging => {}
400 // The actual return type is a struct, but the ABI
401 // adaptation code has cast it into some scalar type. The
402 // code that follows is the only reliable way I have
403 // found to do a transform like i64 -> {i32,i32}.
404 // Basically we dump the data onto the stack then memcpy it.
406 // Other approaches I tried:
407 // - Casting rust ret pointer to the foreign type and using Store
408 // is (a) unsafe if size of foreign type > size of rust type and
409 // (b) runs afoul of strict aliasing rules, yielding invalid
410 // assembly under -O (specifically, the store gets removed).
411 // - Truncating foreign type to correct integral type and then
412 // bitcasting to the struct type yields invalid cast errors.
413 let llscratch = base::alloca(bcx, llforeign_ret_ty, "__cast");
414 Store(bcx, llforeign_retval, llscratch);
415 let llscratch_i8 = BitCast(bcx, llscratch, Type::i8(ccx).ptr_to());
416 let llretptr_i8 = BitCast(bcx, llretptr, Type::i8(ccx).ptr_to());
417 let llrust_size = machine::llsize_of_store(ccx, llrust_ret_ty);
418 let llforeign_align = machine::llalign_of_min(ccx, llforeign_ret_ty);
419 let llrust_align = machine::llalign_of_min(ccx, llrust_ret_ty);
420 let llalign = cmp::min(llforeign_align, llrust_align);
421 debug!("llrust_size={}", llrust_size);
422 base::call_memcpy(bcx, llretptr_i8, llscratch_i8,
423 C_uint(ccx, llrust_size), llalign as u32);
430 // feature gate SIMD types in FFI, since I (huonw) am not sure the
431 // ABIs are handled at all correctly.
432 fn gate_simd_ffi(tcx: &ty::ctxt, decl: &ast::FnDecl, ty: &ty::BareFnTy) {
433 if !tcx.sess.features.borrow().simd_ffi {
434 let check = |ast_ty: &ast::Ty, ty: ty::Ty| {
435 if ty::type_is_simd(tcx, ty) {
436 tcx.sess.span_err(ast_ty.span,
437 &format!("use of SIMD type `{}` in FFI is highly experimental and \
438 may result in invalid code",
439 pprust::ty_to_string(ast_ty))[]);
440 tcx.sess.span_help(ast_ty.span,
441 "add #![feature(simd_ffi)] to the crate attributes to enable");
445 for (input, ty) in decl.inputs.iter().zip(sig.inputs.iter()) {
446 check(&*input.ty, *ty)
448 if let ast::Return(ref ty) = decl.output {
449 check(&**ty, sig.output.unwrap())
454 pub fn trans_foreign_mod(ccx: &CrateContext, foreign_mod: &ast::ForeignMod) {
455 let _icx = push_ctxt("foreign::trans_foreign_mod");
456 for foreign_item in &foreign_mod.items {
457 let lname = link_name(&**foreign_item);
459 if let ast::ForeignItemFn(ref decl, _) = foreign_item.node {
460 match foreign_mod.abi {
461 Rust | RustIntrinsic => {}
463 let ty = ty::node_id_to_type(ccx.tcx(), foreign_item.id);
465 ty::ty_bare_fn(_, bft) => gate_simd_ffi(ccx.tcx(), &**decl, bft),
466 _ => ccx.tcx().sess.span_bug(foreign_item.span,
467 "foreign fn's sty isn't a bare_fn_ty?")
470 register_foreign_item_fn(ccx, abi, ty,
472 // Unlike for other items, we shouldn't call
473 // `base::update_linkage` here. Foreign items have
474 // special linkage requirements, which are handled
475 // inside `foreign::register_*`.
480 ccx.item_symbols().borrow_mut().insert(foreign_item.id,
481 lname.get().to_string());
485 ///////////////////////////////////////////////////////////////////////////
486 // Rust functions with foreign ABIs
488 // These are normal Rust functions defined with foreign ABIs. For
489 // now, and perhaps forever, we translate these using a "layer of
490 // indirection". That is, given a Rust declaration like:
492 // extern "C" fn foo(i: u32) -> u32 { ... }
494 // we will generate a function like:
498 // foo0(&r, NULL, i);
503 // void foo0(uint32_t *r, void *env, uint32_t i) { ... }
505 // Here the (internal) `foo0` function follows the Rust ABI as normal,
506 // where the `foo` function follows the C ABI. We rely on LLVM to
507 // inline the one into the other. Of course we could just generate the
508 // correct code in the first place, but this is much simpler.
510 pub fn decl_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
514 let tys = foreign_types_for_fn_ty(ccx, t);
515 let llfn_ty = lltype_for_fn_from_foreign_types(ccx, &tys);
516 let cconv = match t.sty {
517 ty::ty_bare_fn(_, ref fn_ty) => {
518 llvm_calling_convention(ccx, fn_ty.abi)
520 _ => panic!("expected bare fn in decl_rust_fn_with_foreign_abi")
522 let llfn = base::decl_fn(ccx, name, cconv, llfn_ty, ty::FnConverging(ty::mk_nil(ccx.tcx())));
523 add_argument_attributes(&tys, llfn);
524 debug!("decl_rust_fn_with_foreign_abi(llfn_ty={}, llfn={})",
525 ccx.tn().type_to_string(llfn_ty), ccx.tn().val_to_string(llfn));
529 pub fn register_rust_fn_with_foreign_abi(ccx: &CrateContext,
532 node_id: ast::NodeId)
534 let _icx = push_ctxt("foreign::register_foreign_fn");
536 let tys = foreign_types_for_id(ccx, node_id);
537 let llfn_ty = lltype_for_fn_from_foreign_types(ccx, &tys);
538 let t = ty::node_id_to_type(ccx.tcx(), node_id);
539 let cconv = match t.sty {
540 ty::ty_bare_fn(_, ref fn_ty) => {
541 llvm_calling_convention(ccx, fn_ty.abi)
543 _ => panic!("expected bare fn in register_rust_fn_with_foreign_abi")
545 let llfn = base::register_fn_llvmty(ccx, sp, sym, node_id, cconv, llfn_ty);
546 add_argument_attributes(&tys, llfn);
547 debug!("register_rust_fn_with_foreign_abi(node_id={}, llfn_ty={}, llfn={})",
548 node_id, ccx.tn().type_to_string(llfn_ty), ccx.tn().val_to_string(llfn));
552 pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
555 attrs: &[ast::Attribute],
557 param_substs: &Substs<'tcx>,
559 hash: Option<&str>) {
560 let _icx = push_ctxt("foreign::build_foreign_fn");
562 let fnty = ty::node_id_to_type(ccx.tcx(), id);
563 let mty = monomorphize::apply_param_substs(ccx.tcx(), param_substs, &fnty);
564 let tys = foreign_types_for_fn_ty(ccx, mty);
566 unsafe { // unsafe because we call LLVM operations
567 // Build up the Rust function (`foo0` above).
568 let llrustfn = build_rust_fn(ccx, decl, body, param_substs, attrs, id, hash);
570 // Build up the foreign wrapper (`foo` above).
571 return build_wrap_fn(ccx, llrustfn, llwrapfn, &tys, mty);
574 fn build_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
577 param_substs: &Substs<'tcx>,
578 attrs: &[ast::Attribute],
583 let _icx = push_ctxt("foreign::foreign::build_rust_fn");
585 let t = ty::node_id_to_type(tcx, id);
586 let t = monomorphize::apply_param_substs(tcx, param_substs, &t);
588 let ps = ccx.tcx().map.with_path(id, |path| {
589 let abi = Some(ast_map::PathName(special_idents::clownshoe_abi.name));
590 link::mangle(path.chain(abi.into_iter()), hash)
593 // Compute the type that the function would have if it were just a
594 // normal Rust function. This will be the type of the wrappee fn.
596 ty::ty_bare_fn(_, ref f) => {
597 assert!(f.abi != Rust && f.abi != RustIntrinsic);
600 ccx.sess().bug(&format!("build_rust_fn: extern fn {} has ty {}, \
601 expected a bare fn ty",
602 ccx.tcx().map.path_to_string(id),
607 debug!("build_rust_fn: path={} id={} t={}",
608 ccx.tcx().map.path_to_string(id),
611 let llfn = base::decl_internal_rust_fn(ccx, t, &ps[]);
612 base::set_llvm_fn_attrs(ccx, attrs, llfn);
613 base::trans_fn(ccx, decl, body, llfn, param_substs, id, &[]);
617 unsafe fn build_wrap_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
620 tys: &ForeignTypes<'tcx>,
622 let _icx = push_ctxt(
623 "foreign::trans_rust_fn_with_foreign_abi::build_wrap_fn");
626 debug!("build_wrap_fn(llrustfn={}, llwrapfn={}, t={})",
627 ccx.tn().val_to_string(llrustfn),
628 ccx.tn().val_to_string(llwrapfn),
631 // Avoid all the Rust generation stuff and just generate raw
634 // We want to generate code like this:
638 // foo0(&r, NULL, i);
642 let ptr = "the block\0".as_ptr();
643 let the_block = llvm::LLVMAppendBasicBlockInContext(ccx.llcx(), llwrapfn,
646 let builder = ccx.builder();
647 builder.position_at_end(the_block);
649 // Array for the arguments we will pass to the rust function.
650 let mut llrust_args = Vec::new();
651 let mut next_foreign_arg_counter: c_uint = 0;
652 let mut next_foreign_arg = |pad: bool| -> c_uint {
653 next_foreign_arg_counter += if pad {
658 next_foreign_arg_counter - 1
661 // If there is an out pointer on the foreign function
662 let foreign_outptr = {
663 if tys.fn_ty.ret_ty.is_indirect() {
664 Some(get_param(llwrapfn, next_foreign_arg(false)))
670 // Push Rust return pointer, using null if it will be unused.
671 let rust_uses_outptr = match tys.fn_sig.output {
672 ty::FnConverging(ret_ty) => type_of::return_uses_outptr(ccx, ret_ty),
673 ty::FnDiverging => false
675 let return_alloca: Option<ValueRef>;
676 let llrust_ret_ty = tys.llsig.llret_ty;
677 let llrust_retptr_ty = llrust_ret_ty.ptr_to();
678 if rust_uses_outptr {
679 // Rust expects to use an outpointer. If the foreign fn
680 // also uses an outpointer, we can reuse it, but the types
681 // may vary, so cast first to the Rust type. If the
682 // foreign fn does NOT use an outpointer, we will have to
683 // alloca some scratch space on the stack.
684 match foreign_outptr {
685 Some(llforeign_outptr) => {
686 debug!("out pointer, foreign={}",
687 ccx.tn().val_to_string(llforeign_outptr));
689 builder.bitcast(llforeign_outptr, llrust_retptr_ty);
690 debug!("out pointer, foreign={} (casted)",
691 ccx.tn().val_to_string(llrust_retptr));
692 llrust_args.push(llrust_retptr);
693 return_alloca = None;
697 let slot = builder.alloca(llrust_ret_ty, "return_alloca");
698 debug!("out pointer, \
702 ccx.tn().val_to_string(slot),
703 ccx.tn().type_to_string(llrust_ret_ty),
704 tys.fn_sig.output.repr(tcx));
705 llrust_args.push(slot);
706 return_alloca = Some(slot);
710 // Rust does not expect an outpointer. If the foreign fn
711 // does use an outpointer, then we will do a store of the
712 // value that the Rust fn returns.
713 return_alloca = None;
716 // Build up the arguments to the call to the rust function.
717 // Careful to adapt for cases where the native convention uses
718 // a pointer and Rust does not or vice versa.
719 for i in 0..tys.fn_sig.inputs.len() {
720 let rust_ty = tys.fn_sig.inputs[i];
721 let llrust_ty = tys.llsig.llarg_tys[i];
722 let rust_indirect = type_of::arg_is_indirect(ccx, rust_ty);
723 let llforeign_arg_ty = tys.fn_ty.arg_tys[i];
724 let foreign_indirect = llforeign_arg_ty.is_indirect();
726 if llforeign_arg_ty.is_ignore() {
727 debug!("skipping ignored arg #{}", i);
728 llrust_args.push(C_undef(llrust_ty));
733 let foreign_index = next_foreign_arg(llforeign_arg_ty.pad.is_some());
734 let mut llforeign_arg = get_param(llwrapfn, foreign_index);
736 debug!("llforeign_arg {}{}: {}", "#",
737 i, ccx.tn().val_to_string(llforeign_arg));
738 debug!("rust_indirect = {}, foreign_indirect = {}",
739 rust_indirect, foreign_indirect);
741 // Ensure that the foreign argument is indirect (by
742 // pointer). It makes adapting types easier, since we can
743 // always just bitcast pointers.
744 if !foreign_indirect {
745 llforeign_arg = if ty::type_is_bool(rust_ty) {
746 let lltemp = builder.alloca(Type::bool(ccx), "");
747 builder.store(builder.zext(llforeign_arg, Type::bool(ccx)), lltemp);
750 let lltemp = builder.alloca(val_ty(llforeign_arg), "");
751 builder.store(llforeign_arg, lltemp);
756 // If the types in the ABI and the Rust types don't match,
757 // bitcast the llforeign_arg pointer so it matches the types
759 if llforeign_arg_ty.cast.is_some() {
760 assert!(!foreign_indirect);
761 llforeign_arg = builder.bitcast(llforeign_arg, llrust_ty.ptr_to());
764 let llrust_arg = if rust_indirect {
767 if ty::type_is_bool(rust_ty) {
768 let tmp = builder.load_range_assert(llforeign_arg, 0, 2, llvm::False);
769 builder.trunc(tmp, Type::i1(ccx))
770 } else if type_of::type_of(ccx, rust_ty).is_aggregate() {
771 // We want to pass small aggregates as immediate values, but using an aggregate
772 // LLVM type for this leads to bad optimizations, so its arg type is an
773 // appropriately sized integer and we have to convert it
774 let tmp = builder.bitcast(llforeign_arg,
775 type_of::arg_type_of(ccx, rust_ty).ptr_to());
778 builder.load(llforeign_arg)
782 debug!("llrust_arg {}{}: {}", "#",
783 i, ccx.tn().val_to_string(llrust_arg));
784 llrust_args.push(llrust_arg);
787 // Perform the call itself
788 debug!("calling llrustfn = {}, t = {}",
789 ccx.tn().val_to_string(llrustfn), t.repr(ccx.tcx()));
790 let attributes = base::get_fn_llvm_attributes(ccx, t);
791 let llrust_ret_val = builder.call(llrustfn, &llrust_args, Some(attributes));
793 // Get the return value where the foreign fn expects it.
794 let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast {
796 None => tys.fn_ty.ret_ty.ty
798 match foreign_outptr {
799 None if !tys.llsig.ret_def => {
800 // Function returns `()` or `bot`, which in Rust is the LLVM
801 // type "{}" but in foreign ABIs is "Void".
805 None if rust_uses_outptr => {
806 // Rust uses an outpointer, but the foreign ABI does not. Load.
807 let llrust_outptr = return_alloca.unwrap();
808 let llforeign_outptr_casted =
809 builder.bitcast(llrust_outptr, llforeign_ret_ty.ptr_to());
810 let llforeign_retval = builder.load(llforeign_outptr_casted);
811 builder.ret(llforeign_retval);
814 None if llforeign_ret_ty != llrust_ret_ty => {
815 // Neither ABI uses an outpointer, but the types don't
816 // quite match. Must cast. Probably we should try and
817 // examine the types and use a concrete llvm cast, but
818 // right now we just use a temp memory location and
819 // bitcast the pointer, which is the same thing the
820 // old wrappers used to do.
821 let lltemp = builder.alloca(llforeign_ret_ty, "");
822 let lltemp_casted = builder.bitcast(lltemp, llrust_ret_ty.ptr_to());
823 builder.store(llrust_ret_val, lltemp_casted);
824 let llforeign_retval = builder.load(lltemp);
825 builder.ret(llforeign_retval);
829 // Neither ABI uses an outpointer, and the types
830 // match. Easy peasy.
831 builder.ret(llrust_ret_val);
834 Some(llforeign_outptr) if !rust_uses_outptr => {
835 // Foreign ABI requires an out pointer, but Rust doesn't.
836 // Store Rust return value.
837 let llforeign_outptr_casted =
838 builder.bitcast(llforeign_outptr, llrust_retptr_ty);
839 builder.store(llrust_ret_val, llforeign_outptr_casted);
844 // Both ABIs use outpointers. Easy peasy.
851 ///////////////////////////////////////////////////////////////////////////
852 // General ABI Support
854 // This code is kind of a confused mess and needs to be reworked given
855 // the massive simplifications that have occurred.
857 pub fn link_name(i: &ast::ForeignItem) -> InternedString {
858 match attr::first_attr_value_str_by_name(&i.attrs[], "link_name") {
859 Some(ln) => ln.clone(),
860 None => match weak_lang_items::link_name(&i.attrs[]) {
862 None => token::get_ident(i.ident),
867 /// The ForeignSignature is the LLVM types of the arguments/return type of a function. Note that
868 /// these LLVM types are not quite the same as the LLVM types would be for a native Rust function
869 /// because foreign functions just plain ignore modes. They also don't pass aggregate values by
870 /// pointer like we do.
871 fn foreign_signature<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
872 fn_sig: &ty::FnSig<'tcx>,
873 arg_tys: &[Ty<'tcx>])
875 let llarg_tys = arg_tys.iter().map(|&arg| foreign_arg_type_of(ccx, arg)).collect();
876 let (llret_ty, ret_def) = match fn_sig.output {
877 ty::FnConverging(ret_ty) =>
878 (type_of::foreign_arg_type_of(ccx, ret_ty), !return_type_is_void(ccx, ret_ty)),
880 (Type::nil(ccx), false)
883 llarg_tys: llarg_tys,
889 fn foreign_types_for_id<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
890 id: ast::NodeId) -> ForeignTypes<'tcx> {
891 foreign_types_for_fn_ty(ccx, ty::node_id_to_type(ccx.tcx(), id))
894 fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
895 ty: Ty<'tcx>) -> ForeignTypes<'tcx> {
896 let fn_sig = match ty.sty {
897 ty::ty_bare_fn(_, ref fn_ty) => &fn_ty.sig,
898 _ => ccx.sess().bug("foreign_types_for_fn_ty called on non-function type")
900 let fn_sig = ty::erase_late_bound_regions(ccx.tcx(), fn_sig);
901 let llsig = foreign_signature(ccx, &fn_sig, &fn_sig.inputs);
902 let fn_ty = cabi::compute_abi_info(ccx,
906 debug!("foreign_types_for_fn_ty(\
912 ccx.tn().types_to_str(&llsig.llarg_tys[]),
913 ccx.tn().type_to_string(llsig.llret_ty),
914 ccx.tn().types_to_str(&fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>()),
915 ccx.tn().type_to_string(fn_ty.ret_ty.ty),
925 fn lltype_for_fn_from_foreign_types(ccx: &CrateContext, tys: &ForeignTypes) -> Type {
926 let mut llargument_tys = Vec::new();
928 let ret_ty = tys.fn_ty.ret_ty;
929 let llreturn_ty = if ret_ty.is_indirect() {
930 llargument_tys.push(ret_ty.ty.ptr_to());
939 for &arg_ty in &tys.fn_ty.arg_tys {
940 if arg_ty.is_ignore() {
945 Some(ty) => llargument_tys.push(ty),
949 let llarg_ty = if arg_ty.is_indirect() {
958 llargument_tys.push(llarg_ty);
961 if tys.fn_sig.variadic {
962 Type::variadic_func(&llargument_tys, &llreturn_ty)
964 Type::func(&llargument_tys[], &llreturn_ty)
968 pub fn lltype_for_foreign_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
969 ty: Ty<'tcx>) -> Type {
970 lltype_for_fn_from_foreign_types(ccx, &foreign_types_for_fn_ty(ccx, ty))
973 fn add_argument_attributes(tys: &ForeignTypes,
975 let mut i = if tys.fn_ty.ret_ty.is_indirect() {
981 match tys.fn_ty.ret_ty.attr {
982 Some(attr) => unsafe {
983 llvm::LLVMAddFunctionAttribute(llfn, i as c_uint, attr.bits() as u64);
990 for &arg_ty in &tys.fn_ty.arg_tys {
991 if arg_ty.is_ignore() {
995 if arg_ty.pad.is_some() { i += 1; }
998 Some(attr) => unsafe {
999 llvm::LLVMAddFunctionAttribute(llfn, i as c_uint, attr.bits() as u64);