]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/callee.rs
54cc561e8041505065d1eae557cacb52072dec58
[rust.git] / src / librustc_trans / callee.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Handles translation of callees as well as other call-related
12 //! things.  Callees are a superset of normal rust values and sometimes
13 //! have different representations.  In particular, top-level fn items
14 //! and methods are represented as just a fn ptr and not a full
15 //! closure.
16
17 use attributes;
18 use common::{self, CodegenCx};
19 use consts;
20 use declare;
21 use llvm::{self, ValueRef};
22 use monomorphize::Instance;
23 use type_of::LayoutLlvmExt;
24
25 use rustc::hir::def_id::DefId;
26 use rustc::ty::{self, TypeFoldable};
27 use rustc::ty::layout::LayoutOf;
28 use rustc::traits;
29 use rustc::ty::subst::Substs;
30 use rustc_back::PanicStrategy;
31
32 /// Translates a reference to a fn/method item, monomorphizing and
33 /// inlining as it goes.
34 ///
35 /// # Parameters
36 ///
37 /// - `cx`: the crate context
38 /// - `instance`: the instance to be instantiated
39 pub fn get_fn<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
40                         instance: Instance<'tcx>)
41                         -> ValueRef
42 {
43     let tcx = cx.tcx;
44
45     debug!("get_fn(instance={:?})", instance);
46
47     assert!(!instance.substs.needs_infer());
48     assert!(!instance.substs.has_escaping_regions());
49     assert!(!instance.substs.has_param_types());
50
51     let fn_ty = instance.ty(cx.tcx);
52     if let Some(&llfn) = cx.instances.borrow().get(&instance) {
53         return llfn;
54     }
55
56     let sym = tcx.symbol_name(instance);
57     debug!("get_fn({:?}: {:?}) => {}", instance, fn_ty, sym);
58
59     // Create a fn pointer with the substituted signature.
60     let fn_ptr_ty = tcx.mk_fn_ptr(common::ty_fn_sig(cx, fn_ty));
61     let llptrty = cx.layout_of(fn_ptr_ty).llvm_type(cx);
62
63     let llfn = if let Some(llfn) = declare::get_declared_value(cx, &sym) {
64         // This is subtle and surprising, but sometimes we have to bitcast
65         // the resulting fn pointer.  The reason has to do with external
66         // functions.  If you have two crates that both bind the same C
67         // library, they may not use precisely the same types: for
68         // example, they will probably each declare their own structs,
69         // which are distinct types from LLVM's point of view (nominal
70         // types).
71         //
72         // Now, if those two crates are linked into an application, and
73         // they contain inlined code, you can wind up with a situation
74         // where both of those functions wind up being loaded into this
75         // application simultaneously. In that case, the same function
76         // (from LLVM's point of view) requires two types. But of course
77         // LLVM won't allow one function to have two types.
78         //
79         // What we currently do, therefore, is declare the function with
80         // one of the two types (whichever happens to come first) and then
81         // bitcast as needed when the function is referenced to make sure
82         // it has the type we expect.
83         //
84         // This can occur on either a crate-local or crate-external
85         // reference. It also occurs when testing libcore and in some
86         // other weird situations. Annoying.
87         if common::val_ty(llfn) != llptrty {
88             debug!("get_fn: casting {:?} to {:?}", llfn, llptrty);
89             consts::ptrcast(llfn, llptrty)
90         } else {
91             debug!("get_fn: not casting pointer!");
92             llfn
93         }
94     } else {
95         let llfn = declare::declare_fn(cx, &sym, fn_ty);
96         assert_eq!(common::val_ty(llfn), llptrty);
97         debug!("get_fn: not casting pointer!");
98
99         if instance.def.is_inline(tcx) {
100             attributes::inline(llfn, attributes::InlineAttr::Hint);
101         }
102         attributes::from_fn_attrs(cx, llfn, instance.def.def_id());
103
104         let instance_def_id = instance.def_id();
105
106         // Perhaps questionable, but we assume that anything defined
107         // *in Rust code* may unwind. Foreign items like `extern "C" {
108         // fn foo(); }` are assumed not to unwind **unless** they have
109         // a `#[unwind]` attribute.
110         if tcx.sess.panic_strategy() == PanicStrategy::Unwind {
111             if !tcx.is_foreign_item(instance_def_id) {
112                 attributes::unwind(llfn, true);
113             }
114         }
115
116         // Apply an appropriate linkage/visibility value to our item that we
117         // just declared.
118         //
119         // This is sort of subtle. Inside our codegen unit we started off
120         // compilation by predefining all our own `TransItem` instances. That
121         // is, everything we're translating ourselves is already defined. That
122         // means that anything we're actually translating ourselves will have
123         // hit the above branch in `get_declared_value`. As a result, we're
124         // guaranteed here that we're declaring a symbol that won't get defined,
125         // or in other words we're referencing a foreign value.
126         //
127         // So because this is a foreign value we blanket apply an external
128         // linkage directive because it's coming from a different object file.
129         // The visibility here is where it gets tricky. This symbol could be
130         // referencing some foreign crate or foreign library (an `extern`
131         // block) in which case we want to leave the default visibility. We may
132         // also, though, have multiple codegen units.
133         //
134         // In the situation of multiple codegen units this function may be
135         // referencing a function from another codegen unit. If we're
136         // indeed referencing a symbol in another codegen unit then we're in one
137         // of two cases:
138         //
139         //  * This is a symbol defined in a foreign crate and we're just
140         //    monomorphizing in another codegen unit. In this case this symbols
141         //    is for sure not exported, so both codegen units will be using
142         //    hidden visibility. Hence, we apply a hidden visibility here.
143         //
144         //  * This is a symbol defined in our local crate. If the symbol in the
145         //    other codegen unit is also not exported then like with the foreign
146         //    case we apply a hidden visibility. If the symbol is exported from
147         //    the foreign object file, however, then we leave this at the
148         //    default visibility as we'll just import it naturally.
149         unsafe {
150             llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage);
151
152             if cx.tcx.is_translated_item(instance_def_id) {
153                 if instance_def_id.is_local() {
154                     if !cx.tcx.is_reachable_non_generic(instance_def_id) {
155                         llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
156                     }
157                 } else {
158                     llvm::LLVMRustSetVisibility(llfn, llvm::Visibility::Hidden);
159                 }
160             }
161         }
162
163         if cx.use_dll_storage_attrs &&
164             tcx.is_dllimport_foreign_item(instance_def_id)
165         {
166             unsafe {
167                 llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport);
168             }
169         }
170
171         llfn
172     };
173
174     cx.instances.borrow_mut().insert(instance, llfn);
175
176     llfn
177 }
178
179 pub fn resolve_and_get_fn<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
180                                     def_id: DefId,
181                                     substs: &'tcx Substs<'tcx>)
182                                     -> ValueRef
183 {
184     get_fn(
185         cx,
186         ty::Instance::resolve(
187             cx.tcx,
188             ty::ParamEnv::empty(traits::Reveal::All),
189             def_id,
190             substs
191         ).unwrap()
192     )
193 }