foreign.rs 32.9 KB
Newer Older
1
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 3 4 5 6 7 8 9 10
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

11

12 13
use back::{link};
use lib::llvm::llvm;
14
use lib::llvm::{ValueRef, CallConv, StructRetAttribute};
15
use lib;
16
use middle::trans::base::push_ctxt;
17
use middle::trans::base;
18
use middle::trans::build::*;
19
use middle::trans::builder::noname;
20
use middle::trans::cabi;
21
use middle::trans::common::*;
22 23
use middle::trans::machine;
use middle::trans::type_::Type;
24
use middle::trans::type_of::*;
25
use middle::trans::type_of;
E
Erick Tryzelaar 已提交
26
use middle::ty::FnSig;
27 28 29
use middle::ty;
use std::cmp;
use std::libc::c_uint;
30
use std::vec;
31 32
use syntax::abi::{Cdecl, Aapcs, C, AbiSet, Win64};
use syntax::abi::{RustIntrinsic, Rust, Stdcall, Fastcall, System};
33
use syntax::codemap::Span;
34
use syntax::parse::token::special_idents;
35
use syntax::{ast};
36
use syntax::{attr, ast_map};
37
use util::ppaux::{Repr, UserString};
38

39 40
///////////////////////////////////////////////////////////////////////////
// Type definitions
41

42 43
struct ForeignTypes {
    /// Rust signature of the function
44 45
    fn_sig: ty::FnSig,

46 47 48 49
    /// Adapter object for handling native ABI rules (trust me, you
    /// don't want to know)
    fn_ty: cabi::FnType,

50 51 52 53
    /// LLVM types that will appear on the foreign function
    llsig: LlvmSignature,

    /// True if there is a return value (not bottom, not unit)
54
    ret_def: bool,
55
}
56

57
struct LlvmSignature {
58
    // LLVM versions of the types of this function's arguments.
J
James Miller 已提交
59
    llarg_tys: ~[Type],
60

61 62 63 64 65
    // LLVM version of the type that this function returns.  Note that
    // this *may not be* the declared return type of the foreign
    // function, because the foreign function may opt to return via an
    // out pointer.
    llret_ty: Type,
66

67 68
    // True if *Rust* would use an outpointer for this function.
    sret: bool,
69 70
}

71

72 73
///////////////////////////////////////////////////////////////////////////
// Calls to external functions
74

75
pub fn llvm_calling_convention(ccx: &CrateContext,
76
                               abis: AbiSet) -> Option<CallConv> {
A
Alex Crichton 已提交
77
    let os = ccx.sess.targ_cfg.os;
78
    let arch = ccx.sess.targ_cfg.arch;
A
Alex Crichton 已提交
79
    abis.for_target(os, arch).map(|abi| {
80
        match abi {
81 82
            RustIntrinsic => {
                // Intrinsics are emitted by monomorphic fn
A
Alex Crichton 已提交
83
                ccx.sess.bug(format!("Asked to register intrinsic fn"));
84
            }
85

86 87 88
            Rust => {
                // FIXME(#3678) Implement linking to foreign fns with Rust ABI
                ccx.sess.unimpl(
A
Alex Crichton 已提交
89
                    format!("Foreign functions with Rust ABI"));
90
            }
91

A
Alex Crichton 已提交
92 93 94
            // It's the ABI's job to select this, not us.
            System => ccx.sess.bug("System abi should be selected elsewhere"),

95 96 97
            Stdcall => lib::llvm::X86StdcallCallConv,
            Fastcall => lib::llvm::X86FastcallCallConv,
            C => lib::llvm::CCallConv,
E
Eric Holk 已提交
98
            Win64 => lib::llvm::X86_64_Win64,
99

A
Alex Crichton 已提交
100
            // These API constants ought to be more specific...
101 102 103 104 105
            Cdecl => lib::llvm::CCallConv,
            Aapcs => lib::llvm::CCallConv,
        }
    })
}
106

J
James Miller 已提交
107

108
pub fn register_foreign_item_fn(ccx: @CrateContext,
109
                                abis: AbiSet,
110 111
                                path: &ast_map::Path,
                                foreign_item: @ast::ForeignItem) -> ValueRef {
112 113 114 115
    /*!
     * Registers a foreign function found in a library.
     * Just adds a LLVM global.
     */
116

117
    debug!("register_foreign_item_fn(abis={}, \
A
Alex Crichton 已提交
118 119
            path={}, \
            foreign_item.id={:?})",
120 121 122
           abis.repr(ccx.tcx),
           path.repr(ccx.tcx),
           foreign_item.id);
123

124 125
    let cc = match llvm_calling_convention(ccx, abis) {
        Some(cc) => cc,
126
        None => {
127
            ccx.sess.span_fatal(foreign_item.span,
A
Alex Crichton 已提交
128
                format!("ABI `{}` has no suitable ABI \
129
                      for target architecture \
A
Alex Crichton 已提交
130
                      in module {}",
131
                     abis.user_string(ccx.tcx),
132 133 134
                     ast_map::path_to_str(*path,
                                          ccx.sess.intr())));
        }
135 136
    };

137 138 139
    // Register the function as a C extern fn
    let lname = link_name(ccx, foreign_item);
    let tys = foreign_types_for_id(ccx, foreign_item.id);
140

141 142 143 144 145 146
    // Make sure the calling convention is right for variadic functions
    // (should've been caught if not in typeck)
    if tys.fn_sig.variadic {
        assert!(cc == lib::llvm::CCallConv);
    }

147 148
    // Create the LLVM value for the C extern fn
    let llfn_ty = lltype_for_fn_from_foreign_types(&tys);
149 150 151 152 153 154 155 156 157 158

    let llfn;
    {
        let mut externs = ccx.externs.borrow_mut();
        llfn = base::get_extern_fn(externs.get(),
                                   ccx.llmod,
                                   lname,
                                   cc,
                                   llfn_ty);
    };
159
    add_argument_attributes(&tys, llfn);
160

161 162
    return llfn;
}
163

164 165
pub fn trans_native_call<'a>(
                         bcx: &'a Block<'a>,
166 167 168
                         callee_ty: ty::t,
                         llfn: ValueRef,
                         llretptr: ValueRef,
169
                         llargs_rust: &[ValueRef],
170 171
                         passed_arg_tys: ~[ty::t])
                         -> &'a Block<'a> {
172 173 174 175 176 177 178 179 180 181 182
    /*!
     * Prepares a call to a native function. This requires adapting
     * from the Rust argument passing rules to the native rules.
     *
     * # Parameters
     *
     * - `callee_ty`: Rust type for the function we are calling
     * - `llfn`: the function pointer we are calling
     * - `llretptr`: where to store the return value of the function
     * - `llargs_rust`: a list of the argument values, prepared
     *   as they would be if calling a Rust function
183 184 185 186
     * - `passed_arg_tys`: Rust type for the arguments. Normally we
     *   can derive these from callee_ty but in the case of variadic
     *   functions passed_arg_tys will include the Rust type of all
     *   the arguments including the ones not specified in the fn's signature.
187
     */
188

189 190
    let ccx = bcx.ccx();
    let tcx = bcx.tcx();
191

192
    debug!("trans_native_call(callee_ty={}, \
A
Alex Crichton 已提交
193 194
            llfn={}, \
            llretptr={})",
195 196 197
           callee_ty.repr(tcx),
           ccx.tn.val_to_str(llfn),
           ccx.tn.val_to_str(llretptr));
198

199 200 201 202
    let (fn_abis, fn_sig) = match ty::get(callee_ty).sty {
        ty::ty_bare_fn(ref fn_ty) => (fn_ty.abis, fn_ty.sig.clone()),
        _ => ccx.sess.bug("trans_native_call called on non-function type")
    };
203
    let llsig = foreign_signature(ccx, &fn_sig, passed_arg_tys);
D
Daniel Micay 已提交
204
    let ret_def = !ty::type_is_voidish(bcx.tcx(), fn_sig.output);
205 206 207 208 209
    let fn_type = cabi::compute_abi_info(ccx,
                                         llsig.llarg_tys,
                                         llsig.llret_ty,
                                         ret_def);

J
Jyun-Yan You 已提交
210
    let arg_tys: &[cabi::ArgType] = fn_type.arg_tys;
211 212 213 214 215 216 217

    let mut llargs_foreign = ~[];

    // If the foreign ABI expects return value by pointer, supply the
    // pointer that Rust gave us. Sometimes we have to bitcast
    // because foreign fns return slightly different (but equivalent)
    // views on the same type (e.g., i64 in place of {i32,i32}).
J
Jyun-Yan You 已提交
218 219 220
    if fn_type.ret_ty.is_indirect() {
        match fn_type.ret_ty.cast {
            Some(ty) => {
221
                let llcastedretptr =
J
Jyun-Yan You 已提交
222
                    BitCast(bcx, llretptr, ty.ptr_to());
223
                llargs_foreign.push(llcastedretptr);
J
Jyun-Yan You 已提交
224 225
            }
            None => {
226 227
                llargs_foreign.push(llretptr);
            }
228
        }
J
Jyun-Yan You 已提交
229
    }
230

231 232
    for (i, &llarg_rust) in llargs_rust.iter().enumerate() {
        let mut llarg_rust = llarg_rust;
233

234
        // Does Rust pass this argument by pointer?
235
        let rust_indirect = type_of::arg_is_indirect(ccx, passed_arg_tys[i]);
236

237
        debug!("argument {}, llarg_rust={}, rust_indirect={}, arg_ty={}",
238 239 240 241
               i,
               ccx.tn.val_to_str(llarg_rust),
               rust_indirect,
               ccx.tn.type_to_str(arg_tys[i].ty));
242

243 244 245
        // Ensure that we always have the Rust value indirectly,
        // because it makes bitcasting easier.
        if !rust_indirect {
246
            let scratch = base::alloca(bcx, type_of::type_of(ccx, passed_arg_tys[i]), "__arg");
247 248
            Store(bcx, llarg_rust, scratch);
            llarg_rust = scratch;
249 250
        }

251
        debug!("llarg_rust={} (after indirection)",
252
               ccx.tn.val_to_str(llarg_rust));
253

254
        // Check whether we need to do any casting
J
Jyun-Yan You 已提交
255 256 257
        match arg_tys[i].cast {
            Some(ty) => llarg_rust = BitCast(bcx, llarg_rust, ty.ptr_to()),
            None => ()
258
        }
259

260
        debug!("llarg_rust={} (after casting)",
261
               ccx.tn.val_to_str(llarg_rust));
262

263
        // Finally, load the value if needed for the foreign ABI
J
Jyun-Yan You 已提交
264
        let foreign_indirect = arg_tys[i].is_indirect();
265 266 267 268
        let llarg_foreign = if foreign_indirect {
            llarg_rust
        } else {
            Load(bcx, llarg_rust)
269 270
        };

271
        debug!("argument {}, llarg_foreign={}",
272
               i, ccx.tn.val_to_str(llarg_foreign));
273

J
Jyun-Yan You 已提交
274 275 276 277 278
        // fill padding with undef value
        match arg_tys[i].pad {
            Some(ty) => llargs_foreign.push(C_undef(ty)),
            None => ()
        }
279
        llargs_foreign.push(llarg_foreign);
280 281
    }

282 283 284 285 286
    let cc = match llvm_calling_convention(ccx, fn_abis) {
        Some(cc) => cc,
        None => {
            // FIXME(#8357) We really ought to report a span here
            ccx.sess.fatal(
A
Alex Crichton 已提交
287
                format!("ABI string `{}` has no suitable ABI \
288 289 290 291
                      for target architecture",
                     fn_abis.user_string(ccx.tcx)));
        }
    };
292

293 294 295
    // A function pointer is called without the declaration available, so we have to apply
    // any attributes with ABI implications directly to the call instruction. Right now, the
    // only attribute we need to worry about is `sret`.
296
    let attrs;
J
Jyun-Yan You 已提交
297
    if fn_type.ret_ty.is_indirect() {
298 299 300 301 302
        attrs = &[(1, StructRetAttribute)];
    } else {
        attrs = &[];
    }
    let llforeign_retval = CallWithConv(bcx, llfn, llargs_foreign, cc, attrs);
303

304 305 306 307 308
    // If the function we just called does not use an outpointer,
    // store the result into the rust outpointer. Cast the outpointer
    // type to match because some ABIs will use a different type than
    // the Rust type. e.g., a {u32,u32} struct could be returned as
    // u64.
J
Jyun-Yan You 已提交
309
    if ret_def && !fn_type.ret_ty.is_indirect() {
310
        let llrust_ret_ty = llsig.llret_ty;
J
Jyun-Yan You 已提交
311 312 313 314
        let llforeign_ret_ty = match fn_type.ret_ty.cast {
            Some(ty) => ty,
            None => fn_type.ret_ty.ty
        };
315

316 317 318 319
        debug!("llretptr={}", ccx.tn.val_to_str(llretptr));
        debug!("llforeign_retval={}", ccx.tn.val_to_str(llforeign_retval));
        debug!("llrust_ret_ty={}", ccx.tn.type_to_str(llrust_ret_ty));
        debug!("llforeign_ret_ty={}", ccx.tn.type_to_str(llforeign_ret_ty));
320

321 322
        if llrust_ret_ty == llforeign_ret_ty {
            Store(bcx, llforeign_retval, llretptr);
323
        } else {
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
            // The actual return type is a struct, but the ABI
            // adaptation code has cast it into some scalar type.  The
            // code that follows is the only reliable way I have
            // found to do a transform like i64 -> {i32,i32}.
            // Basically we dump the data onto the stack then memcpy it.
            //
            // Other approaches I tried:
            // - Casting rust ret pointer to the foreign type and using Store
            //   is (a) unsafe if size of foreign type > size of rust type and
            //   (b) runs afoul of strict aliasing rules, yielding invalid
            //   assembly under -O (specifically, the store gets removed).
            // - Truncating foreign type to correct integral type and then
            //   bitcasting to the struct type yields invalid cast errors.
            let llscratch = base::alloca(bcx, llforeign_ret_ty, "__cast");
            Store(bcx, llforeign_retval, llscratch);
            let llscratch_i8 = BitCast(bcx, llscratch, Type::i8().ptr_to());
            let llretptr_i8 = BitCast(bcx, llretptr, Type::i8().ptr_to());
            let llrust_size = machine::llsize_of_store(ccx, llrust_ret_ty);
            let llforeign_align = machine::llalign_of_min(ccx, llforeign_ret_ty);
            let llrust_align = machine::llalign_of_min(ccx, llrust_ret_ty);
344
            let llalign = cmp::min(llforeign_align, llrust_align);
345
            debug!("llrust_size={:?}", llrust_size);
346 347
            base::call_memcpy(bcx, llretptr_i8, llscratch_i8,
                              C_uint(ccx, llrust_size), llalign as u32);
348
        }
349 350
    }

351 352
    return bcx;
}
353

354
pub fn trans_foreign_mod(ccx: @CrateContext,
355
                         foreign_mod: &ast::ForeignMod) {
356 357
    let _icx = push_ctxt("foreign::trans_foreign_mod");
    for &foreign_item in foreign_mod.items.iter() {
358
        match foreign_item.node {
359
            ast::ForeignItemFn(..) => {
P
Patrick Walton 已提交
360 361 362
                let items = ccx.tcx.items.borrow();
                let (abis, mut path) =
                    match items.get().get_copy(&foreign_item.id) {
363
                        ast_map::NodeForeignItem(_, abis, _, path) => {
P
Patrick Walton 已提交
364 365 366 367 368 369 370
                            (abis, (*path).clone())
                        }
                        _ => {
                            fail!("Unable to find foreign item in tcx.items \
                                   table.")
                        }
                    };
371
                if !(abis.is_rust() || abis.is_intrinsic()) {
372
                    path.push(ast_map::PathName(foreign_item.ident));
373 374 375 376 377 378
                    register_foreign_item_fn(ccx, abis, &path, foreign_item);
                }
            }
            _ => ()
        }

379
        let lname = link_name(ccx, foreign_item);
380 381
        let mut item_symbols = ccx.item_symbols.borrow_mut();
        item_symbols.get().insert(foreign_item.id, lname.to_owned());
382 383 384
    }
}

385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
///////////////////////////////////////////////////////////////////////////
// Rust functions with foreign ABIs
//
// These are normal Rust functions defined with foreign ABIs.  For
// now, and perhaps forever, we translate these using a "layer of
// indirection". That is, given a Rust declaration like:
//
//     extern "C" fn foo(i: u32) -> u32 { ... }
//
// we will generate a function like:
//
//     S foo(T i) {
//         S r;
//         foo0(&r, NULL, i);
//         return r;
//     }
//
//     #[inline_always]
//     void foo0(uint32_t *r, void *env, uint32_t i) { ... }
//
// Here the (internal) `foo0` function follows the Rust ABI as normal,
// where the `foo` function follows the C ABI. We rely on LLVM to
// inline the one into the other. Of course we could just generate the
// correct code in the first place, but this is much simpler.

410
pub fn register_rust_fn_with_foreign_abi(ccx: @CrateContext,
411
                                         sp: Span,
412 413 414 415 416 417 418
                                         sym: ~str,
                                         node_id: ast::NodeId)
                                         -> ValueRef {
    let _icx = push_ctxt("foreign::register_foreign_fn");

    let tys = foreign_types_for_id(ccx, node_id);
    let llfn_ty = lltype_for_fn_from_foreign_types(&tys);
419 420 421 422 423 424 425 426
    let t = ty::node_id_to_type(ccx.tcx, node_id);
    let cconv = match ty::get(t).sty {
        ty::ty_bare_fn(ref fn_ty) => {
            let c = llvm_calling_convention(ccx, fn_ty.abis);
            c.unwrap_or(lib::llvm::CCallConv)
        }
        _ => lib::llvm::CCallConv
    };
427 428 429 430
    let llfn = base::register_fn_llvmty(ccx,
                                        sp,
                                        sym,
                                        node_id,
431
                                        cconv,
432 433
                                        llfn_ty);
    add_argument_attributes(&tys, llfn);
434
    debug!("register_rust_fn_with_foreign_abi(node_id={:?}, llfn_ty={}, llfn={})",
435 436 437 438
           node_id, ccx.tn.type_to_str(llfn_ty), ccx.tn.val_to_str(llfn));
    llfn
}

439
pub fn trans_rust_fn_with_foreign_abi(ccx: @CrateContext,
440 441
                                      path: &ast_map::Path,
                                      decl: &ast::FnDecl,
442
                                      body: &ast::Block,
443
                                      attrs: &[ast::Attribute],
444 445
                                      llwrapfn: ValueRef,
                                      id: ast::NodeId) {
446
    let _icx = push_ctxt("foreign::build_foreign_fn");
447 448 449 450
    let tys = foreign_types_for_id(ccx, id);

    unsafe { // unsafe because we call LLVM operations
        // Build up the Rust function (`foo0` above).
451
        let llrustfn = build_rust_fn(ccx, path, decl, body, attrs, id);
452 453 454 455

        // Build up the foreign wrapper (`foo` above).
        return build_wrap_fn(ccx, llrustfn, llwrapfn, &tys);
    }
456

457
    fn build_rust_fn(ccx: @CrateContext,
458 459
                     path: &ast_map::Path,
                     decl: &ast::FnDecl,
460
                     body: &ast::Block,
461
                     attrs: &[ast::Attribute],
462
                     id: ast::NodeId)
463
                     -> ValueRef {
464
        let _icx = push_ctxt("foreign::foreign::build_rust_fn");
465 466
        let tcx = ccx.tcx;
        let t = ty::node_id_to_type(tcx, id);
467
        let ps = link::mangle_internal_name_by_path(
468
            ccx, vec::append_one((*path).clone(), ast_map::PathName(
469 470
                special_idents::clownshoe_abi
            )));
471

472 473 474
        // Compute the type that the function would have if it were just a
        // normal Rust function. This will be the type of the wrappee fn.
        let f = match ty::get(t).sty {
475 476
            ty::ty_bare_fn(ref f) => {
                assert!(!f.abis.is_rust() && !f.abis.is_intrinsic());
477
                f
478 479
            }
            _ => {
A
Alex Crichton 已提交
480
                ccx.sess.bug(format!("build_rust_fn: extern fn {} has ty {}, \
481 482 483 484 485 486
                                  expected a bare fn ty",
                                  path.repr(tcx),
                                  t.repr(tcx)));
            }
        };

487
        debug!("build_rust_fn: path={} id={:?} t={}",
488 489
               path.repr(tcx),
               id,
490
               t.repr(tcx));
491

492
        let llfndecl = base::decl_internal_rust_fn(ccx, None, f.sig.inputs, f.sig.output, ps);
493
        base::set_llvm_fn_attrs(attrs, llfndecl);
494 495 496 497 498
        base::trans_fn(ccx,
                       (*path).clone(),
                       decl,
                       body,
                       llfndecl,
499
                       None,
500 501
                       None,
                       id,
502
                       None,
503
                       []);
B
Brian Anderson 已提交
504
        return llfndecl;
505 506
    }

507
    unsafe fn build_wrap_fn(ccx: @CrateContext,
508 509 510 511 512 513 514
                            llrustfn: ValueRef,
                            llwrapfn: ValueRef,
                            tys: &ForeignTypes) {
        let _icx = push_ctxt(
            "foreign::trans_rust_fn_with_foreign_abi::build_wrap_fn");
        let tcx = ccx.tcx;

515
        debug!("build_wrap_fn(llrustfn={}, llwrapfn={})",
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
               ccx.tn.val_to_str(llrustfn),
               ccx.tn.val_to_str(llwrapfn));

        // Avoid all the Rust generation stuff and just generate raw
        // LLVM here.
        //
        // We want to generate code like this:
        //
        //     S foo(T i) {
        //         S r;
        //         foo0(&r, NULL, i);
        //         return r;
        //     }

        let the_block =
531
            "the block".with_c_str(
532 533 534 535 536 537 538 539
                |s| llvm::LLVMAppendBasicBlockInContext(ccx.llcx, llwrapfn, s));

        let builder = ccx.builder.B;
        llvm::LLVMPositionBuilderAtEnd(builder, the_block);

        // Array for the arguments we will pass to the rust function.
        let mut llrust_args = ~[];
        let mut next_foreign_arg_counter: c_uint = 0;
540 541 542 543 544 545 546
        let next_foreign_arg: |pad: bool| -> c_uint = |pad: bool| {
            next_foreign_arg_counter += if pad {
                2
            } else {
                1
            };
            next_foreign_arg_counter - 1
547
        };
548

549 550
        // If there is an out pointer on the foreign function
        let foreign_outptr = {
J
Jyun-Yan You 已提交
551 552
            if tys.fn_ty.ret_ty.is_indirect() {
                Some(llvm::LLVMGetParam(llwrapfn, next_foreign_arg(false)))
553 554 555 556
            } else {
                None
            }
        };
557

558 559
        // Push Rust return pointer, using null if it will be unused.
        let rust_uses_outptr =
560
            type_of::return_uses_outptr(ccx, tys.fn_sig.output);
561 562 563 564 565 566 567
        let return_alloca: Option<ValueRef>;
        let llrust_ret_ty = tys.llsig.llret_ty;
        let llrust_retptr_ty = llrust_ret_ty.ptr_to();
        if rust_uses_outptr {
            // Rust expects to use an outpointer. If the foreign fn
            // also uses an outpointer, we can reuse it, but the types
            // may vary, so cast first to the Rust type. If the
568
            // foreign fn does NOT use an outpointer, we will have to
569 570 571
            // alloca some scratch space on the stack.
            match foreign_outptr {
                Some(llforeign_outptr) => {
572
                    debug!("out pointer, foreign={}",
573 574 575 576 577 578
                           ccx.tn.val_to_str(llforeign_outptr));
                    let llrust_retptr =
                        llvm::LLVMBuildBitCast(builder,
                                               llforeign_outptr,
                                               llrust_ret_ty.ptr_to().to_ref(),
                                               noname());
579
                    debug!("out pointer, foreign={} (casted)",
580 581 582
                           ccx.tn.val_to_str(llrust_retptr));
                    llrust_args.push(llrust_retptr);
                    return_alloca = None;
583 584
                }

585 586
                None => {
                    let slot = {
587
                        "return_alloca".with_c_str(
588 589 590 591
                            |s| llvm::LLVMBuildAlloca(builder,
                                                      llrust_ret_ty.to_ref(),
                                                      s))
                    };
592
                    debug!("out pointer, \
A
Alex Crichton 已提交
593 594 595
                            allocad={}, \
                            llrust_ret_ty={}, \
                            return_ty={}",
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
                           ccx.tn.val_to_str(slot),
                           ccx.tn.type_to_str(llrust_ret_ty),
                           tys.fn_sig.output.repr(tcx));
                    llrust_args.push(slot);
                    return_alloca = Some(slot);
                }
            }
        } else {
            // Rust does not expect an outpointer. If the foreign fn
            // does use an outpointer, then we will do a store of the
            // value that the Rust fn returns.
            return_alloca = None;
        };

        // Push an (null) env pointer
        let env_pointer = base::null_env_ptr(ccx);
612
        debug!("env pointer={}", ccx.tn.val_to_str(env_pointer));
613 614 615 616 617 618 619 620 621
        llrust_args.push(env_pointer);

        // Build up the arguments to the call to the rust function.
        // Careful to adapt for cases where the native convention uses
        // a pointer and Rust does not or vice versa.
        for i in range(0, tys.fn_sig.inputs.len()) {
            let rust_ty = tys.fn_sig.inputs[i];
            let llrust_ty = tys.llsig.llarg_tys[i];
            let rust_indirect = type_of::arg_is_indirect(ccx, rust_ty);
J
Jyun-Yan You 已提交
622 623 624 625 626
            let llforeign_arg_ty = tys.fn_ty.arg_tys[i];
            let foreign_indirect = llforeign_arg_ty.is_indirect();

            // skip padding
            let foreign_index = next_foreign_arg(llforeign_arg_ty.pad.is_some());
627 628
            let mut llforeign_arg = llvm::LLVMGetParam(llwrapfn, foreign_index);

629
            debug!("llforeign_arg \\#{}: {}",
630
                   i, ccx.tn.val_to_str(llforeign_arg));
631
            debug!("rust_indirect = {}, foreign_indirect = {}",
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
                   rust_indirect, foreign_indirect);

            // Ensure that the foreign argument is indirect (by
            // pointer).  It makes adapting types easier, since we can
            // always just bitcast pointers.
            if !foreign_indirect {
                let lltemp =
                    llvm::LLVMBuildAlloca(
                        builder, val_ty(llforeign_arg).to_ref(), noname());
                llvm::LLVMBuildStore(
                    builder, llforeign_arg, lltemp);
                llforeign_arg = lltemp;
            }

            // If the types in the ABI and the Rust types don't match,
            // bitcast the llforeign_arg pointer so it matches the types
            // Rust expects.
J
Jyun-Yan You 已提交
649
            if llforeign_arg_ty.cast.is_some() {
650 651 652 653
                assert!(!foreign_indirect);
                llforeign_arg = llvm::LLVMBuildBitCast(
                    builder, llforeign_arg,
                    llrust_ty.ptr_to().to_ref(), noname());
654 655
            }

656 657
            let llrust_arg = if rust_indirect {
                llforeign_arg
658
            } else {
659 660 661
                llvm::LLVMBuildLoad(builder, llforeign_arg, noname())
            };

662
            debug!("llrust_arg \\#{}: {}",
663 664 665 666 667
                   i, ccx.tn.val_to_str(llrust_arg));
            llrust_args.push(llrust_arg);
        }

        // Perform the call itself
668 669 670
        debug!("calling llrustfn = {}", ccx.tn.val_to_str(llrustfn));
        let llrust_ret_val = llvm::LLVMBuildCall(builder, llrustfn, llrust_args.as_ptr(),
                                                 llrust_args.len() as c_uint, noname());
671 672

        // Get the return value where the foreign fn expects it.
J
Jyun-Yan You 已提交
673 674 675 676
        let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast {
            Some(ty) => ty,
            None => tys.fn_ty.ret_ty.ty
        };
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
        match foreign_outptr {
            None if !tys.ret_def => {
                // Function returns `()` or `bot`, which in Rust is the LLVM
                // type "{}" but in foreign ABIs is "Void".
                llvm::LLVMBuildRetVoid(builder);
            }

            None if rust_uses_outptr => {
                // Rust uses an outpointer, but the foreign ABI does not. Load.
                let llrust_outptr = return_alloca.unwrap();
                let llforeign_outptr_casted =
                    llvm::LLVMBuildBitCast(builder,
                                           llrust_outptr,
                                           llforeign_ret_ty.ptr_to().to_ref(),
                                           noname());
                let llforeign_retval =
                    llvm::LLVMBuildLoad(builder, llforeign_outptr_casted, noname());
                llvm::LLVMBuildRet(builder, llforeign_retval);
            }

            None if llforeign_ret_ty != llrust_ret_ty => {
                // Neither ABI uses an outpointer, but the types don't
                // quite match. Must cast. Probably we should try and
                // examine the types and use a concrete llvm cast, but
                // right now we just use a temp memory location and
                // bitcast the pointer, which is the same thing the
                // old wrappers used to do.
                let lltemp =
                    llvm::LLVMBuildAlloca(
                        builder, llforeign_ret_ty.to_ref(), noname());
                let lltemp_casted =
                    llvm::LLVMBuildBitCast(builder,
                                           lltemp,
                                           llrust_ret_ty.ptr_to().to_ref(),
                                           noname());
                llvm::LLVMBuildStore(
                    builder, llrust_ret_val, lltemp_casted);
                let llforeign_retval =
                    llvm::LLVMBuildLoad(builder, lltemp, noname());
                llvm::LLVMBuildRet(builder, llforeign_retval);
            }

            None => {
                // Neither ABI uses an outpointer, and the types
                // match. Easy peasy.
                llvm::LLVMBuildRet(builder, llrust_ret_val);
            }

            Some(llforeign_outptr) if !rust_uses_outptr => {
                // Foreign ABI requires an out pointer, but Rust doesn't.
                // Store Rust return value.
                let llforeign_outptr_casted =
                    llvm::LLVMBuildBitCast(builder,
                                           llforeign_outptr,
                                           llrust_retptr_ty.to_ref(),
                                           noname());
                llvm::LLVMBuildStore(
                    builder, llrust_ret_val, llforeign_outptr_casted);
                llvm::LLVMBuildRetVoid(builder);
            }

            Some(_) => {
                // Both ABIs use outpointers. Easy peasy.
                llvm::LLVMBuildRetVoid(builder);
741
            }
742
        }
743 744
    }
}
745

746 747 748 749 750 751
///////////////////////////////////////////////////////////////////////////
// General ABI Support
//
// This code is kind of a confused mess and needs to be reworked given
// the massive simplifications that have occurred.

752
pub fn link_name(ccx: &CrateContext, i: @ast::ForeignItem) -> @str {
753 754 755
     match attr::first_attr_value_str_by_name(i.attrs, "link_name") {
        None => ccx.sess.str_of(i.ident),
        Some(ln) => ln,
756
    }
757
}
758

759
fn foreign_signature(ccx: &CrateContext, fn_sig: &ty::FnSig, arg_tys: &[ty::t])
760 761 762 763 764 765 766 767
                     -> LlvmSignature {
    /*!
     * The ForeignSignature is the LLVM types of the arguments/return type
     * of a function.  Note that these LLVM types are not quite the same
     * as the LLVM types would be for a native Rust function because foreign
     * functions just plain ignore modes.  They also don't pass aggregate
     * values by pointer like we do.
     */
768

769
    let llarg_tys = arg_tys.map(|&arg| type_of(ccx, arg));
770 771 772 773
    let llret_ty = type_of::type_of(ccx, fn_sig.output);
    LlvmSignature {
        llarg_tys: llarg_tys,
        llret_ty: llret_ty,
774
        sret: type_of::return_uses_outptr(ccx, fn_sig.output),
775
    }
776
}
777

778
fn foreign_types_for_id(ccx: &CrateContext,
779 780
                        id: ast::NodeId) -> ForeignTypes {
    foreign_types_for_fn_ty(ccx, ty::node_id_to_type(ccx.tcx, id))
781 782
}

783
fn foreign_types_for_fn_ty(ccx: &CrateContext,
784 785 786 787 788
                           ty: ty::t) -> ForeignTypes {
    let fn_sig = match ty::get(ty).sty {
        ty::ty_bare_fn(ref fn_ty) => fn_ty.sig.clone(),
        _ => ccx.sess.bug("foreign_types_for_fn_ty called on non-function type")
    };
789
    let llsig = foreign_signature(ccx, &fn_sig, fn_sig.inputs);
D
Daniel Micay 已提交
790
    let ret_def = !ty::type_is_voidish(ccx.tcx, fn_sig.output);
791 792 793 794
    let fn_ty = cabi::compute_abi_info(ccx,
                                       llsig.llarg_tys,
                                       llsig.llret_ty,
                                       ret_def);
795
    debug!("foreign_types_for_fn_ty(\
A
Alex Crichton 已提交
796 797 798 799
           ty={}, \
           llsig={} -> {}, \
           fn_ty={} -> {}, \
           ret_def={}",
800 801 802 803 804 805 806 807 808 809 810 811 812 813
           ty.repr(ccx.tcx),
           ccx.tn.types_to_str(llsig.llarg_tys),
           ccx.tn.type_to_str(llsig.llret_ty),
           ccx.tn.types_to_str(fn_ty.arg_tys.map(|t| t.ty)),
           ccx.tn.type_to_str(fn_ty.ret_ty.ty),
           ret_def);

    ForeignTypes {
        fn_sig: fn_sig,
        llsig: llsig,
        ret_def: ret_def,
        fn_ty: fn_ty
    }
}
814

815
fn lltype_for_fn_from_foreign_types(tys: &ForeignTypes) -> Type {
J
Jyun-Yan You 已提交
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
    let mut llargument_tys = ~[];

    let ret_ty = tys.fn_ty.ret_ty;
    let llreturn_ty = if ret_ty.is_indirect() {
        llargument_tys.push(ret_ty.ty.ptr_to());
        Type::void()
    } else {
        match ret_ty.cast {
            Some(ty) => ty,
            None => ret_ty.ty
        }
    };

    for &arg_ty in tys.fn_ty.arg_tys.iter() {
        // add padding
        match arg_ty.pad {
            Some(ty) => llargument_tys.push(ty),
            None => ()
        }

        let llarg_ty = if arg_ty.is_indirect() {
            arg_ty.ty.ptr_to()
        } else {
            match arg_ty.cast {
                Some(ty) => ty,
                None => arg_ty.ty
            }
        };

        llargument_tys.push(llarg_ty);
    }

848 849 850 851 852
    if tys.fn_sig.variadic {
        Type::variadic_func(llargument_tys, &llreturn_ty)
    } else {
        Type::func(llargument_tys, &llreturn_ty)
    }
853 854
}

855
pub fn lltype_for_foreign_fn(ccx: &CrateContext, ty: ty::t) -> Type {
856 857 858
    let fn_types = foreign_types_for_fn_ty(ccx, ty);
    lltype_for_fn_from_foreign_types(&fn_types)
}
859

860 861
fn add_argument_attributes(tys: &ForeignTypes,
                           llfn: ValueRef) {
J
Jyun-Yan You 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
    let mut i = 0;

    if tys.fn_ty.ret_ty.is_indirect() {
        match tys.fn_ty.ret_ty.attr {
            Some(attr) => {
                let llarg = get_param(llfn, i);
                unsafe {
                    llvm::LLVMAddAttribute(llarg, attr as c_uint);
                }
            }
            None => {}
        }

        i += 1;
    }

    for &arg_ty in tys.fn_ty.arg_tys.iter() {
        // skip padding
        if arg_ty.pad.is_some() { i += 1; }

        match arg_ty.attr {
883 884 885 886 887 888 889 890
            Some(attr) => {
                let llarg = get_param(llfn, i);
                unsafe {
                    llvm::LLVMAddAttribute(llarg, attr as c_uint);
                }
            }
            None => ()
        }
J
Jyun-Yan You 已提交
891 892

        i += 1;
893
    }
894
}