]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/declare.rs
Fixes doc important trait display on mobile
[rust.git] / src / librustc_trans / declare.rs
1 // Copyright 2012-2015 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 //! Declare various LLVM values.
11 //!
12 //! Prefer using functions and methods from this module rather than calling LLVM
13 //! functions directly. These functions do some additional work to ensure we do
14 //! the right thing given the preconceptions of trans.
15 //!
16 //! Some useful guidelines:
17 //!
18 //! * Use declare_* family of methods if you are declaring, but are not
19 //!   interested in defining the ValueRef they return.
20 //! * Use define_* family of methods when you might be defining the ValueRef.
21 //! * When in doubt, define.
22
23 use llvm::{self, ValueRef};
24 use llvm::AttributePlace::Function;
25 use rustc::ty::Ty;
26 use rustc::session::config::Sanitizer;
27 use rustc_back::PanicStrategy;
28 use abi::{Abi, FnType};
29 use attributes;
30 use context::CrateContext;
31 use common;
32 use type_::Type;
33 use value::Value;
34
35 use std::ffi::CString;
36
37
38 /// Declare a global value.
39 ///
40 /// If there’s a value with the same name already declared, the function will
41 /// return its ValueRef instead.
42 pub fn declare_global(ccx: &CrateContext, name: &str, ty: Type) -> llvm::ValueRef {
43     debug!("declare_global(name={:?})", name);
44     let namebuf = CString::new(name).unwrap_or_else(|_|{
45         bug!("name {:?} contains an interior null byte", name)
46     });
47     unsafe {
48         llvm::LLVMRustGetOrInsertGlobal(ccx.llmod(), namebuf.as_ptr(), ty.to_ref())
49     }
50 }
51
52
53 /// Declare a function.
54 ///
55 /// If there’s a value with the same name already declared, the function will
56 /// update the declaration and return existing ValueRef instead.
57 fn declare_raw_fn(ccx: &CrateContext, name: &str, callconv: llvm::CallConv, ty: Type) -> ValueRef {
58     debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty);
59     let namebuf = CString::new(name).unwrap_or_else(|_|{
60         bug!("name {:?} contains an interior null byte", name)
61     });
62     let llfn = unsafe {
63         llvm::LLVMRustGetOrInsertFunction(ccx.llmod(), namebuf.as_ptr(), ty.to_ref())
64     };
65
66     llvm::SetFunctionCallConv(llfn, callconv);
67     // Function addresses in Rust are never significant, allowing functions to
68     // be merged.
69     llvm::SetUnnamedAddr(llfn, true);
70
71     if ccx.tcx().sess.opts.cg.no_redzone
72         .unwrap_or(ccx.tcx().sess.target.target.options.disable_redzone) {
73         llvm::Attribute::NoRedZone.apply_llfn(Function, llfn);
74     }
75
76     if let Some(ref sanitizer) = ccx.tcx().sess.opts.debugging_opts.sanitizer {
77         match *sanitizer {
78             Sanitizer::Address => {
79                 llvm::Attribute::SanitizeAddress.apply_llfn(Function, llfn);
80             },
81             Sanitizer::Memory => {
82                 llvm::Attribute::SanitizeMemory.apply_llfn(Function, llfn);
83             },
84             Sanitizer::Thread => {
85                 llvm::Attribute::SanitizeThread.apply_llfn(Function, llfn);
86             },
87             _ => {}
88         }
89     }
90
91     match ccx.tcx().sess.opts.cg.opt_level.as_ref().map(String::as_ref) {
92         Some("s") => {
93             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
94         },
95         Some("z") => {
96             llvm::Attribute::MinSize.apply_llfn(Function, llfn);
97             llvm::Attribute::OptimizeForSize.apply_llfn(Function, llfn);
98         },
99         _ => {},
100     }
101
102     if ccx.tcx().sess.panic_strategy() != PanicStrategy::Unwind {
103         attributes::unwind(llfn, false);
104     }
105
106     llfn
107 }
108
109
110 /// Declare a C ABI function.
111 ///
112 /// Only use this for foreign function ABIs and glue. For Rust functions use
113 /// `declare_fn` instead.
114 ///
115 /// If there’s a value with the same name already declared, the function will
116 /// update the declaration and return existing ValueRef instead.
117 pub fn declare_cfn(ccx: &CrateContext, name: &str, fn_type: Type) -> ValueRef {
118     declare_raw_fn(ccx, name, llvm::CCallConv, fn_type)
119 }
120
121
122 /// Declare a Rust function.
123 ///
124 /// If there’s a value with the same name already declared, the function will
125 /// update the declaration and return existing ValueRef instead.
126 pub fn declare_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, name: &str,
127                             fn_type: Ty<'tcx>) -> ValueRef {
128     debug!("declare_rust_fn(name={:?}, fn_type={:?})", name, fn_type);
129     let sig = common::ty_fn_sig(ccx, fn_type);
130     let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&sig);
131     debug!("declare_rust_fn (after region erasure) sig={:?}", sig);
132
133     let fty = FnType::new(ccx, sig, &[]);
134     let llfn = declare_raw_fn(ccx, name, fty.cconv, fty.llvm_type(ccx));
135
136     // FIXME(canndrew): This is_never should really be an is_uninhabited
137     if sig.output().is_never() {
138         llvm::Attribute::NoReturn.apply_llfn(Function, llfn);
139     }
140
141     if sig.abi != Abi::Rust && sig.abi != Abi::RustCall {
142         attributes::unwind(llfn, false);
143     }
144
145     fty.apply_attrs_llfn(llfn);
146
147     llfn
148 }
149
150
151 /// Declare a global with an intention to define it.
152 ///
153 /// Use this function when you intend to define a global. This function will
154 /// return None if the name already has a definition associated with it. In that
155 /// case an error should be reported to the user, because it usually happens due
156 /// to user’s fault (e.g. misuse of #[no_mangle] or #[export_name] attributes).
157 pub fn define_global(ccx: &CrateContext, name: &str, ty: Type) -> Option<ValueRef> {
158     if get_defined_value(ccx, name).is_some() {
159         None
160     } else {
161         Some(declare_global(ccx, name, ty))
162     }
163 }
164
165 /// Declare a Rust function with an intention to define it.
166 ///
167 /// Use this function when you intend to define a function. This function will
168 /// return panic if the name already has a definition associated with it. This
169 /// can happen with #[no_mangle] or #[export_name], for example.
170 pub fn define_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
171                            name: &str,
172                            fn_type: Ty<'tcx>) -> ValueRef {
173     if get_defined_value(ccx, name).is_some() {
174         ccx.sess().fatal(&format!("symbol `{}` already defined", name))
175     } else {
176         declare_fn(ccx, name, fn_type)
177     }
178 }
179
180 /// Declare a Rust function with an intention to define it.
181 ///
182 /// Use this function when you intend to define a function. This function will
183 /// return panic if the name already has a definition associated with it. This
184 /// can happen with #[no_mangle] or #[export_name], for example.
185 pub fn define_internal_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
186                                     name: &str,
187                                     fn_type: Ty<'tcx>) -> ValueRef {
188     let llfn = define_fn(ccx, name, fn_type);
189     unsafe { llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::InternalLinkage) };
190     llfn
191 }
192
193
194 /// Get declared value by name.
195 pub fn get_declared_value(ccx: &CrateContext, name: &str) -> Option<ValueRef> {
196     debug!("get_declared_value(name={:?})", name);
197     let namebuf = CString::new(name).unwrap_or_else(|_|{
198         bug!("name {:?} contains an interior null byte", name)
199     });
200     let val = unsafe { llvm::LLVMRustGetNamedValue(ccx.llmod(), namebuf.as_ptr()) };
201     if val.is_null() {
202         debug!("get_declared_value: {:?} value is null", name);
203         None
204     } else {
205         debug!("get_declared_value: {:?} => {:?}", name, Value(val));
206         Some(val)
207     }
208 }
209
210 /// Get defined or externally defined (AvailableExternally linkage) value by
211 /// name.
212 pub fn get_defined_value(ccx: &CrateContext, name: &str) -> Option<ValueRef> {
213     get_declared_value(ccx, name).and_then(|val|{
214         let declaration = unsafe {
215             llvm::LLVMIsDeclaration(val) != 0
216         };
217         if !declaration {
218             Some(val)
219         } else {
220             None
221         }
222     })
223 }