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