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.
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.
11 #![allow(non_upper_case_globals)]
12 #![allow(non_camel_case_types)]
13 #![allow(non_snake_case)]
14 #![deny(bare_trait_objects)]
16 pub use self::IntPredicate::*;
17 pub use self::RealPredicate::*;
18 pub use self::AtomicRmwBinOp::*;
19 pub use self::MetadataType::*;
20 pub use self::CodeGenOptSize::*;
21 pub use self::CallConv::*;
22 pub use self::Linkage::*;
24 use std::str::FromStr;
25 use std::string::FromUtf8Error;
28 use std::cell::RefCell;
29 use libc::{self, c_uint, c_char, size_t};
30 use rustc_data_structures::small_c_str::SmallCStr;
40 pub fn into_result(self) -> Result<(), ()> {
42 LLVMRustResult::Success => Ok(()),
43 LLVMRustResult::Failure => Err(()),
48 pub fn AddFunctionAttrStringValue(llfn: &'a Value,
53 LLVMRustAddFunctionAttrStringValue(llfn,
60 #[derive(Copy, Clone)]
61 pub enum AttributePlace {
68 pub fn as_uint(self) -> c_uint {
70 AttributePlace::ReturnValue => 0,
71 AttributePlace::Argument(i) => 1 + i,
72 AttributePlace::Function => !0,
77 #[derive(Copy, Clone, PartialEq)]
79 pub enum CodeGenOptSize {
80 CodeGenOptSizeNone = 0,
81 CodeGenOptSizeDefault = 1,
82 CodeGenOptSizeAggressive = 2,
85 impl FromStr for ArchiveKind {
88 fn from_str(s: &str) -> Result<Self, Self::Err> {
90 "gnu" => Ok(ArchiveKind::K_GNU),
91 "bsd" => Ok(ArchiveKind::K_BSD),
92 "coff" => Ok(ArchiveKind::K_COFF),
99 pub struct RustString {
100 bytes: RefCell<Vec<u8>>,
103 /// Appending to a Rust string -- used by RawRustStringOstream.
105 pub unsafe extern "C" fn LLVMRustStringWriteImpl(sr: &RustString,
108 let slice = slice::from_raw_parts(ptr as *const u8, size as usize);
110 sr.bytes.borrow_mut().extend_from_slice(slice);
113 pub fn SetInstructionCallConv(instr: &'a Value, cc: CallConv) {
115 LLVMSetInstructionCallConv(instr, cc as c_uint);
118 pub fn SetFunctionCallConv(fn_: &'a Value, cc: CallConv) {
120 LLVMSetFunctionCallConv(fn_, cc as c_uint);
124 // Externally visible symbols that might appear in multiple codegen units need to appear in
125 // their own comdat section so that the duplicates can be discarded at link time. This can for
126 // example happen for generics when using multiple codegen units. This function simply uses the
127 // value's name as the comdat value to make sure that it is in a 1-to-1 relationship to the
129 // For more details on COMDAT sections see e.g. http://www.airs.com/blog/archives/52
130 pub fn SetUniqueComdat(llmod: &Module, val: &'a Value) {
132 LLVMRustSetComdat(llmod, val, LLVMGetValueName(val));
136 pub fn UnsetComdat(val: &'a Value) {
138 LLVMRustUnsetComdat(val);
142 pub fn SetUnnamedAddr(global: &'a Value, unnamed: bool) {
144 LLVMSetUnnamedAddr(global, unnamed as Bool);
148 pub fn set_thread_local(global: &'a Value, is_thread_local: bool) {
150 LLVMSetThreadLocal(global, is_thread_local as Bool);
153 pub fn set_thread_local_mode(global: &'a Value, mode: ThreadLocalMode) {
155 LLVMSetThreadLocalMode(global, mode);
160 pub fn apply_llfn(&self, idx: AttributePlace, llfn: &Value) {
161 unsafe { LLVMRustAddFunctionAttribute(llfn, idx.as_uint(), *self) }
164 pub fn apply_callsite(&self, idx: AttributePlace, callsite: &Value) {
165 unsafe { LLVMRustAddCallSiteAttribute(callsite, idx.as_uint(), *self) }
168 pub fn unapply_llfn(&self, idx: AttributePlace, llfn: &Value) {
169 unsafe { LLVMRustRemoveFunctionAttributes(llfn, idx.as_uint(), *self) }
172 pub fn toggle_llfn(&self, idx: AttributePlace, llfn: &Value, set: bool) {
174 self.apply_llfn(idx, llfn);
176 self.unapply_llfn(idx, llfn);
181 // Memory-managed interface to object files.
183 pub struct ObjectFile {
184 pub llof: &'static mut ffi::ObjectFile,
187 unsafe impl Send for ObjectFile {}
190 // This will take ownership of llmb
191 pub fn new(llmb: &'static mut MemoryBuffer) -> Option<ObjectFile> {
193 let llof = LLVMCreateObjectFile(llmb)?;
194 Some(ObjectFile { llof })
199 impl Drop for ObjectFile {
202 LLVMDisposeObjectFile(&mut *(self.llof as *mut _));
207 // Memory-managed interface to section iterators.
209 pub struct SectionIter<'a> {
210 pub llsi: &'a mut SectionIterator<'a>,
213 impl Drop for SectionIter<'a> {
216 LLVMDisposeSectionIterator(&mut *(self.llsi as *mut _));
221 pub fn mk_section_iter(llof: &'a ffi::ObjectFile) -> SectionIter<'a> {
222 unsafe { SectionIter { llsi: LLVMGetSections(llof) } }
225 /// Safe wrapper around `LLVMGetParam`, because segfaults are no fun.
226 pub fn get_param(llfn: &'a Value, index: c_uint) -> &'a Value {
228 assert!(index < LLVMCountParams(llfn),
229 "out of bounds argument access: {} out of {} arguments", index, LLVMCountParams(llfn));
230 LLVMGetParam(llfn, index)
234 pub fn build_string(f: impl FnOnce(&RustString)) -> Result<String, FromUtf8Error> {
235 let sr = RustString {
236 bytes: RefCell::new(Vec::new()),
239 String::from_utf8(sr.bytes.into_inner())
242 pub fn twine_to_string(tr: &Twine) -> String {
244 build_string(|s| LLVMRustWriteTwineToString(tr, s))
245 .expect("got a non-UTF8 Twine from LLVM")
249 pub fn last_error() -> Option<String> {
251 let cstr = LLVMRustGetLastError();
255 let err = CStr::from_ptr(cstr).to_bytes();
256 let err = String::from_utf8_lossy(err).to_string();
257 libc::free(cstr as *mut _);
263 pub struct OperandBundleDef<'a> {
264 pub raw: &'a mut ffi::OperandBundleDef<'a>,
267 impl OperandBundleDef<'a> {
268 pub fn new(name: &str, vals: &[&'a Value]) -> Self {
269 let name = SmallCStr::new(name);
271 LLVMRustBuildOperandBundleDef(name.as_ptr(), vals.as_ptr(), vals.len() as c_uint)
273 OperandBundleDef { raw: def }
276 pub fn from_generic(bundle: &common::OperandBundleDef<'a, &'a Value>) -> Self {
277 Self::new(bundle.name, &[bundle.val])
281 impl Drop for OperandBundleDef<'a> {
284 LLVMRustFreeOperandBundleDef(&mut *(self.raw as *mut _));