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