]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/common.rs
s/AllocType/AllocKind/
[rust.git] / src / librustc_codegen_llvm / common.rs
1 // Copyright 2012-2014 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 #![allow(non_camel_case_types, non_snake_case)]
12
13 //! Code that is useful in various codegen modules.
14
15 use llvm::{self, True, False, Bool, BasicBlock, OperandBundleDef};
16 use abi;
17 use consts;
18 use type_::Type;
19 use type_of::LayoutLlvmExt;
20 use value::Value;
21 use rustc_codegen_ssa::traits::*;
22
23 use rustc::ty::layout::{HasDataLayout, LayoutOf, self, TyLayout, Size};
24 use rustc::mir::interpret::{Scalar, AllocKind, Allocation};
25 use consts::const_alloc_to_llvm;
26 use rustc_codegen_ssa::mir::place::PlaceRef;
27
28 use libc::{c_uint, c_char};
29
30 use syntax::symbol::LocalInternedString;
31 use syntax::ast::Mutability;
32
33 pub use context::CodegenCx;
34
35 /*
36 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
37 *
38 * An "extern" is an LLVM symbol we wind up emitting an undefined external
39 * reference to. This means "we don't have the thing in this compilation unit,
40 * please make sure you link it in at runtime". This could be a reference to
41 * C code found in a C library, or rust code found in a rust crate.
42 *
43 * Most "externs" are implicitly declared (automatically) as a result of a
44 * user declaring an extern _module_ dependency; this causes the rust driver
45 * to locate an extern crate, scan its compilation metadata, and emit extern
46 * declarations for any symbols used by the declaring crate.
47 *
48 * A "foreign" is an extern that references C (or other non-rust ABI) code.
49 * There is no metadata to scan for extern references so in these cases either
50 * a header-digester like bindgen, or manual function prototypes, have to
51 * serve as declarators. So these are usually given explicitly as prototype
52 * declarations, in rust code, with ABI attributes on them noting which ABI to
53 * link via.
54 *
55 * An "upcall" is a foreign call generated by the compiler (not corresponding
56 * to any user-written call in the code) into the runtime library, to perform
57 * some helper task such as bringing a task to life, allocating memory, etc.
58 *
59 */
60
61 /// A structure representing an active landing pad for the duration of a basic
62 /// block.
63 ///
64 /// Each `Block` may contain an instance of this, indicating whether the block
65 /// is part of a landing pad or not. This is used to make decision about whether
66 /// to emit `invoke` instructions (e.g. in a landing pad we don't continue to
67 /// use `invoke`) and also about various function call metadata.
68 ///
69 /// For GNU exceptions (`landingpad` + `resume` instructions) this structure is
70 /// just a bunch of `None` instances (not too interesting), but for MSVC
71 /// exceptions (`cleanuppad` + `cleanupret` instructions) this contains data.
72 /// When inside of a landing pad, each function call in LLVM IR needs to be
73 /// annotated with which landing pad it's a part of. This is accomplished via
74 /// the `OperandBundleDef` value created for MSVC landing pads.
75 pub struct Funclet<'ll> {
76     cleanuppad: &'ll Value,
77     operand: OperandBundleDef<'ll>,
78 }
79
80 impl Funclet<'ll> {
81     pub fn new(cleanuppad: &'ll Value) -> Self {
82         Funclet {
83             cleanuppad,
84             operand: OperandBundleDef::new("funclet", &[cleanuppad]),
85         }
86     }
87
88     pub fn cleanuppad(&self) -> &'ll Value {
89         self.cleanuppad
90     }
91
92     pub fn bundle(&self) -> &OperandBundleDef<'ll> {
93         &self.operand
94     }
95 }
96
97 impl BackendTypes for CodegenCx<'ll, 'tcx> {
98     type Value = &'ll Value;
99     type BasicBlock = &'ll BasicBlock;
100     type Type = &'ll Type;
101     type Funclet = Funclet<'ll>;
102
103     type DIScope = &'ll llvm::debuginfo::DIScope;
104 }
105
106 impl ConstMethods<'tcx> for CodegenCx<'ll, 'tcx> {
107     fn const_null(&self, t: &'ll Type) -> &'ll Value {
108         unsafe {
109             llvm::LLVMConstNull(t)
110         }
111     }
112
113     fn const_undef(&self, t: &'ll Type) -> &'ll Value {
114         unsafe {
115             llvm::LLVMGetUndef(t)
116         }
117     }
118
119     fn const_int(&self, t: &'ll Type, i: i64) -> &'ll Value {
120         unsafe {
121             llvm::LLVMConstInt(t, i as u64, True)
122         }
123     }
124
125     fn const_uint(&self, t: &'ll Type, i: u64) -> &'ll Value {
126         unsafe {
127             llvm::LLVMConstInt(t, i, False)
128         }
129     }
130
131     fn const_uint_big(&self, t: &'ll Type, u: u128) -> &'ll Value {
132         unsafe {
133             let words = [u as u64, (u >> 64) as u64];
134             llvm::LLVMConstIntOfArbitraryPrecision(t, 2, words.as_ptr())
135         }
136     }
137
138     fn const_bool(&self, val: bool) -> &'ll Value {
139         self.const_uint(self.type_i1(), val as u64)
140     }
141
142     fn const_i32(&self, i: i32) -> &'ll Value {
143         self.const_int(self.type_i32(), i as i64)
144     }
145
146     fn const_u32(&self, i: u32) -> &'ll Value {
147         self.const_uint(self.type_i32(), i as u64)
148     }
149
150     fn const_u64(&self, i: u64) -> &'ll Value {
151         self.const_uint(self.type_i64(), i)
152     }
153
154     fn const_usize(&self, i: u64) -> &'ll Value {
155         let bit_size = self.data_layout().pointer_size.bits();
156         if bit_size < 64 {
157             // make sure it doesn't overflow
158             assert!(i < (1<<bit_size));
159         }
160
161         self.const_uint(self.isize_ty, i)
162     }
163
164     fn const_u8(&self, i: u8) -> &'ll Value {
165         self.const_uint(self.type_i8(), i as u64)
166     }
167
168     fn const_cstr(
169         &self,
170         s: LocalInternedString,
171         null_terminated: bool,
172     ) -> &'ll Value {
173         unsafe {
174             if let Some(&llval) = self.const_cstr_cache.borrow().get(&s) {
175                 return llval;
176             }
177
178             let sc = llvm::LLVMConstStringInContext(self.llcx,
179                                                     s.as_ptr() as *const c_char,
180                                                     s.len() as c_uint,
181                                                     !null_terminated as Bool);
182             let sym = self.generate_local_symbol_name("str");
183             let g = self.define_global(&sym[..], self.val_ty(sc)).unwrap_or_else(||{
184                 bug!("symbol `{}` is already defined", sym);
185             });
186             llvm::LLVMSetInitializer(g, sc);
187             llvm::LLVMSetGlobalConstant(g, True);
188             llvm::LLVMRustSetLinkage(g, llvm::Linkage::InternalLinkage);
189
190             self.const_cstr_cache.borrow_mut().insert(s, g);
191             g
192         }
193     }
194
195     fn const_str_slice(&self, s: LocalInternedString) -> &'ll Value {
196         let len = s.len();
197         let cs = consts::ptrcast(self.const_cstr(s, false),
198             self.type_ptr_to(self.layout_of(self.tcx.mk_str()).llvm_type(self)));
199         self.const_fat_ptr(cs, self.const_usize(len as u64))
200     }
201
202     fn const_fat_ptr(
203         &self,
204         ptr: &'ll Value,
205         meta: &'ll Value
206     ) -> &'ll Value {
207         assert_eq!(abi::FAT_PTR_ADDR, 0);
208         assert_eq!(abi::FAT_PTR_EXTRA, 1);
209         self.const_struct(&[ptr, meta], false)
210     }
211
212     fn const_struct(
213         &self,
214         elts: &[&'ll Value],
215         packed: bool
216     ) -> &'ll Value {
217         struct_in_context(self.llcx, elts, packed)
218     }
219
220     fn const_array(&self, ty: &'ll Type, elts: &[&'ll Value]) -> &'ll Value {
221         unsafe {
222             return llvm::LLVMConstArray(ty, elts.as_ptr(), elts.len() as c_uint);
223         }
224     }
225
226     fn const_vector(&self, elts: &[&'ll Value]) -> &'ll Value {
227         unsafe {
228             return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
229         }
230     }
231
232     fn const_bytes(&self, bytes: &[u8]) -> &'ll Value {
233         bytes_in_context(self.llcx, bytes)
234     }
235
236     fn const_get_elt(&self, v: &'ll Value, idx: u64) -> &'ll Value {
237         unsafe {
238             assert_eq!(idx as c_uint as u64, idx);
239             let us = &[idx as c_uint];
240             let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
241
242             debug!("const_get_elt(v={:?}, idx={}, r={:?})",
243                    v, idx, r);
244
245             r
246         }
247     }
248
249     fn const_get_real(&self, v: &'ll Value) -> Option<(f64, bool)> {
250         unsafe {
251             if self.is_const_real(v) {
252                 let mut loses_info: llvm::Bool = ::std::mem::uninitialized();
253                 let r = llvm::LLVMConstRealGetDouble(v, &mut loses_info);
254                 let loses_info = if loses_info == 1 { true } else { false };
255                 Some((r, loses_info))
256             } else {
257                 None
258             }
259         }
260     }
261
262     fn const_to_uint(&self, v: &'ll Value) -> u64 {
263         unsafe {
264             llvm::LLVMConstIntGetZExtValue(v)
265         }
266     }
267
268     fn is_const_integral(&self, v: &'ll Value) -> bool {
269         unsafe {
270             llvm::LLVMIsAConstantInt(v).is_some()
271         }
272     }
273
274     fn is_const_real(&self, v: &'ll Value) -> bool {
275         unsafe {
276             llvm::LLVMIsAConstantFP(v).is_some()
277         }
278     }
279
280     fn const_to_opt_u128(&self, v: &'ll Value, sign_ext: bool) -> Option<u128> {
281         unsafe {
282             if self.is_const_integral(v) {
283                 let (mut lo, mut hi) = (0u64, 0u64);
284                 let success = llvm::LLVMRustConstInt128Get(v, sign_ext,
285                                                            &mut hi, &mut lo);
286                 if success {
287                     Some(hi_lo_to_u128(lo, hi))
288                 } else {
289                     None
290                 }
291             } else {
292                 None
293             }
294         }
295     }
296
297     fn scalar_to_backend(
298         &self,
299         cv: Scalar,
300         layout: &layout::Scalar,
301         llty: &'ll Type,
302     ) -> &'ll Value {
303         let bitsize = if layout.is_bool() { 1 } else { layout.value.size(self).bits() };
304         match cv {
305             Scalar::Bits { size: 0, .. } => {
306                 assert_eq!(0, layout.value.size(self).bytes());
307                 self.const_undef(self.type_ix(0))
308             },
309             Scalar::Bits { bits, size } => {
310                 assert_eq!(size as u64, layout.value.size(self).bytes());
311                 let llval = self.const_uint_big(self.type_ix(bitsize), bits);
312                 if layout.value == layout::Pointer {
313                     unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
314                 } else {
315                     self.const_bitcast(llval, llty)
316                 }
317             },
318             Scalar::Ptr(ptr) => {
319                 let alloc_type = self.tcx.alloc_map.lock().get(ptr.alloc_id);
320                 let base_addr = match alloc_type {
321                     Some(AllocKind::Memory(alloc)) => {
322                         let init = const_alloc_to_llvm(self, alloc);
323                         if alloc.mutability == Mutability::Mutable {
324                             self.static_addr_of_mut(init, alloc.align, None)
325                         } else {
326                             self.static_addr_of(init, alloc.align, None)
327                         }
328                     }
329                     Some(AllocKind::Function(fn_instance)) => {
330                         self.get_fn(fn_instance)
331                     }
332                     Some(AllocKind::Static(def_id)) => {
333                         assert!(self.tcx.is_static(def_id).is_some());
334                         self.get_static(def_id)
335                     }
336                     None => bug!("missing allocation {:?}", ptr.alloc_id),
337                 };
338                 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
339                     self.const_bitcast(base_addr, self.type_i8p()),
340                     &self.const_usize(ptr.offset.bytes()),
341                     1,
342                 ) };
343                 if layout.value != layout::Pointer {
344                     unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
345                 } else {
346                     self.const_bitcast(llval, llty)
347                 }
348             }
349         }
350     }
351
352     fn from_const_alloc(
353         &self,
354         layout: TyLayout<'tcx>,
355         alloc: &Allocation,
356         offset: Size,
357     ) -> PlaceRef<'tcx, &'ll Value> {
358         let init = const_alloc_to_llvm(self, alloc);
359         let base_addr = self.static_addr_of(init, layout.align.abi, None);
360
361         let llval = unsafe { llvm::LLVMConstInBoundsGEP(
362             self.const_bitcast(base_addr, self.type_i8p()),
363             &self.const_usize(offset.bytes()),
364             1,
365         )};
366         let llval = self.const_bitcast(llval, self.type_ptr_to(layout.llvm_type(self)));
367         PlaceRef::new_sized(llval, layout, alloc.align)
368     }
369
370     fn const_ptrcast(&self, val: &'ll Value, ty: &'ll Type) -> &'ll Value {
371         consts::ptrcast(val, ty)
372     }
373 }
374
375 pub fn val_ty(v: &'ll Value) -> &'ll Type {
376     unsafe {
377         llvm::LLVMTypeOf(v)
378     }
379 }
380
381 pub fn bytes_in_context(llcx: &'ll llvm::Context, bytes: &[u8]) -> &'ll Value {
382     unsafe {
383         let ptr = bytes.as_ptr() as *const c_char;
384         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
385     }
386 }
387
388 pub fn struct_in_context(
389     llcx: &'a llvm::Context,
390     elts: &[&'a Value],
391     packed: bool,
392 ) -> &'a Value {
393     unsafe {
394         llvm::LLVMConstStructInContext(llcx,
395                                        elts.as_ptr(), elts.len() as c_uint,
396                                        packed as Bool)
397     }
398 }
399
400 #[inline]
401 fn hi_lo_to_u128(lo: u64, hi: u64) -> u128 {
402     ((hi as u128) << 64) | (lo as u128)
403 }