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