]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/llvm/mod.rs
Rollup merge of #68123 - crlf0710:linked_list_cursor, r=Amanieu
[rust.git] / src / librustc_codegen_llvm / llvm / mod.rs
1 #![allow(non_snake_case)]
2
3 pub use self::AtomicRmwBinOp::*;
4 pub use self::CallConv::*;
5 pub use self::CodeGenOptSize::*;
6 pub use self::IntPredicate::*;
7 pub use self::Linkage::*;
8 pub use self::MetadataType::*;
9 pub use self::RealPredicate::*;
10
11 use libc::c_uint;
12 use rustc_data_structures::small_c_str::SmallCStr;
13 use rustc_llvm::RustString;
14 use std::cell::RefCell;
15 use std::ffi::CStr;
16 use std::str::FromStr;
17 use std::string::FromUtf8Error;
18
19 pub mod archive_ro;
20 pub mod diagnostic;
21 mod ffi;
22
23 pub use self::ffi::*;
24
25 impl LLVMRustResult {
26     pub fn into_result(self) -> Result<(), ()> {
27         match self {
28             LLVMRustResult::Success => Ok(()),
29             LLVMRustResult::Failure => Err(()),
30         }
31     }
32 }
33
34 pub fn AddFunctionAttrStringValue(llfn: &'a Value, idx: AttributePlace, attr: &CStr, value: &CStr) {
35     unsafe {
36         LLVMRustAddFunctionAttrStringValue(llfn, idx.as_uint(), attr.as_ptr(), value.as_ptr())
37     }
38 }
39
40 #[derive(Copy, Clone)]
41 pub enum AttributePlace {
42     ReturnValue,
43     Argument(u32),
44     Function,
45 }
46
47 impl AttributePlace {
48     pub fn as_uint(self) -> c_uint {
49         match self {
50             AttributePlace::ReturnValue => 0,
51             AttributePlace::Argument(i) => 1 + i,
52             AttributePlace::Function => !0,
53         }
54     }
55 }
56
57 #[derive(Copy, Clone, PartialEq)]
58 #[repr(C)]
59 pub enum CodeGenOptSize {
60     CodeGenOptSizeNone = 0,
61     CodeGenOptSizeDefault = 1,
62     CodeGenOptSizeAggressive = 2,
63 }
64
65 impl FromStr for ArchiveKind {
66     type Err = ();
67
68     fn from_str(s: &str) -> Result<Self, Self::Err> {
69         match s {
70             "gnu" => Ok(ArchiveKind::K_GNU),
71             "bsd" => Ok(ArchiveKind::K_BSD),
72             "coff" => Ok(ArchiveKind::K_COFF),
73             _ => Err(()),
74         }
75     }
76 }
77
78 pub fn SetInstructionCallConv(instr: &'a Value, cc: CallConv) {
79     unsafe {
80         LLVMSetInstructionCallConv(instr, cc as c_uint);
81     }
82 }
83 pub fn SetFunctionCallConv(fn_: &'a Value, cc: CallConv) {
84     unsafe {
85         LLVMSetFunctionCallConv(fn_, cc as c_uint);
86     }
87 }
88
89 // Externally visible symbols that might appear in multiple codegen units need to appear in
90 // their own comdat section so that the duplicates can be discarded at link time. This can for
91 // example happen for generics when using multiple codegen units. This function simply uses the
92 // value's name as the comdat value to make sure that it is in a 1-to-1 relationship to the
93 // function.
94 // For more details on COMDAT sections see e.g., http://www.airs.com/blog/archives/52
95 pub fn SetUniqueComdat(llmod: &Module, val: &'a Value) {
96     unsafe {
97         let name = get_value_name(val);
98         LLVMRustSetComdat(llmod, val, name.as_ptr().cast(), name.len());
99     }
100 }
101
102 pub fn UnsetComdat(val: &'a Value) {
103     unsafe {
104         LLVMRustUnsetComdat(val);
105     }
106 }
107
108 pub fn SetUnnamedAddr(global: &'a Value, unnamed: bool) {
109     unsafe {
110         LLVMSetUnnamedAddr(global, unnamed as Bool);
111     }
112 }
113
114 pub fn set_thread_local(global: &'a Value, is_thread_local: bool) {
115     unsafe {
116         LLVMSetThreadLocal(global, is_thread_local as Bool);
117     }
118 }
119 pub fn set_thread_local_mode(global: &'a Value, mode: ThreadLocalMode) {
120     unsafe {
121         LLVMSetThreadLocalMode(global, mode);
122     }
123 }
124
125 impl Attribute {
126     pub fn apply_llfn(&self, idx: AttributePlace, llfn: &Value) {
127         unsafe { LLVMRustAddFunctionAttribute(llfn, idx.as_uint(), *self) }
128     }
129
130     pub fn apply_callsite(&self, idx: AttributePlace, callsite: &Value) {
131         unsafe { LLVMRustAddCallSiteAttribute(callsite, idx.as_uint(), *self) }
132     }
133
134     pub fn unapply_llfn(&self, idx: AttributePlace, llfn: &Value) {
135         unsafe { LLVMRustRemoveFunctionAttributes(llfn, idx.as_uint(), *self) }
136     }
137
138     pub fn toggle_llfn(&self, idx: AttributePlace, llfn: &Value, set: bool) {
139         if set {
140             self.apply_llfn(idx, llfn);
141         } else {
142             self.unapply_llfn(idx, llfn);
143         }
144     }
145 }
146
147 // Memory-managed interface to object files.
148
149 pub struct ObjectFile {
150     pub llof: &'static mut ffi::ObjectFile,
151 }
152
153 unsafe impl Send for ObjectFile {}
154
155 impl ObjectFile {
156     // This will take ownership of llmb
157     pub fn new(llmb: &'static mut MemoryBuffer) -> Option<ObjectFile> {
158         unsafe {
159             let llof = LLVMCreateObjectFile(llmb)?;
160             Some(ObjectFile { llof })
161         }
162     }
163 }
164
165 impl Drop for ObjectFile {
166     fn drop(&mut self) {
167         unsafe {
168             LLVMDisposeObjectFile(&mut *(self.llof as *mut _));
169         }
170     }
171 }
172
173 // Memory-managed interface to section iterators.
174
175 pub struct SectionIter<'a> {
176     pub llsi: &'a mut SectionIterator<'a>,
177 }
178
179 impl Drop for SectionIter<'a> {
180     fn drop(&mut self) {
181         unsafe {
182             LLVMDisposeSectionIterator(&mut *(self.llsi as *mut _));
183         }
184     }
185 }
186
187 pub fn mk_section_iter(llof: &'a ffi::ObjectFile) -> SectionIter<'a> {
188     unsafe { SectionIter { llsi: LLVMGetSections(llof) } }
189 }
190
191 /// Safe wrapper around `LLVMGetParam`, because segfaults are no fun.
192 pub fn get_param(llfn: &'a Value, index: c_uint) -> &'a Value {
193     unsafe {
194         assert!(
195             index < LLVMCountParams(llfn),
196             "out of bounds argument access: {} out of {} arguments",
197             index,
198             LLVMCountParams(llfn)
199         );
200         LLVMGetParam(llfn, index)
201     }
202 }
203
204 /// Safe wrapper for `LLVMGetValueName2` into a byte slice
205 pub fn get_value_name(value: &'a Value) -> &'a [u8] {
206     unsafe {
207         let mut len = 0;
208         let data = LLVMGetValueName2(value, &mut len);
209         std::slice::from_raw_parts(data.cast(), len)
210     }
211 }
212
213 /// Safe wrapper for `LLVMSetValueName2` from a byte slice
214 pub fn set_value_name(value: &Value, name: &[u8]) {
215     unsafe {
216         let data = name.as_ptr().cast();
217         LLVMSetValueName2(value, data, name.len());
218     }
219 }
220
221 pub fn build_string(f: impl FnOnce(&RustString)) -> Result<String, FromUtf8Error> {
222     let sr = RustString { bytes: RefCell::new(Vec::new()) };
223     f(&sr);
224     String::from_utf8(sr.bytes.into_inner())
225 }
226
227 pub fn twine_to_string(tr: &Twine) -> String {
228     unsafe {
229         build_string(|s| LLVMRustWriteTwineToString(tr, s)).expect("got a non-UTF8 Twine from LLVM")
230     }
231 }
232
233 pub fn last_error() -> Option<String> {
234     unsafe {
235         let cstr = LLVMRustGetLastError();
236         if cstr.is_null() {
237             None
238         } else {
239             let err = CStr::from_ptr(cstr).to_bytes();
240             let err = String::from_utf8_lossy(err).to_string();
241             libc::free(cstr as *mut _);
242             Some(err)
243         }
244     }
245 }
246
247 pub struct OperandBundleDef<'a> {
248     pub raw: &'a mut ffi::OperandBundleDef<'a>,
249 }
250
251 impl OperandBundleDef<'a> {
252     pub fn new(name: &str, vals: &[&'a Value]) -> Self {
253         let name = SmallCStr::new(name);
254         let def = unsafe {
255             LLVMRustBuildOperandBundleDef(name.as_ptr(), vals.as_ptr(), vals.len() as c_uint)
256         };
257         OperandBundleDef { raw: def }
258     }
259 }
260
261 impl Drop for OperandBundleDef<'a> {
262     fn drop(&mut self) {
263         unsafe {
264             LLVMRustFreeOperandBundleDef(&mut *(self.raw as *mut _));
265         }
266     }
267 }