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