1 #![allow(non_upper_case_globals)]
6 use crate::abi::{Abi, FnType, LlvmType, PassMode};
7 use crate::context::CodegenCx;
8 use crate::type_::Type;
9 use crate::type_of::LayoutLlvmExt;
10 use crate::builder::Builder;
11 use crate::value::Value;
12 use crate::va_arg::emit_va_arg;
13 use rustc_codegen_ssa::MemFlags;
14 use rustc_codegen_ssa::mir::place::PlaceRef;
15 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
16 use rustc_codegen_ssa::glue;
17 use rustc_codegen_ssa::base::{to_immediate, wants_msvc_seh, compare_simd_types};
18 use rustc::ty::{self, Ty};
19 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, Primitive};
20 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
22 use syntax::ast::{self, FloatTy};
24 use rustc_codegen_ssa::traits::*;
26 use rustc::session::Session;
29 use std::cmp::Ordering;
30 use std::{iter, i128, u128};
32 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
33 let llvm_name = match name {
34 "sqrtf32" => "llvm.sqrt.f32",
35 "sqrtf64" => "llvm.sqrt.f64",
36 "powif32" => "llvm.powi.f32",
37 "powif64" => "llvm.powi.f64",
38 "sinf32" => "llvm.sin.f32",
39 "sinf64" => "llvm.sin.f64",
40 "cosf32" => "llvm.cos.f32",
41 "cosf64" => "llvm.cos.f64",
42 "powf32" => "llvm.pow.f32",
43 "powf64" => "llvm.pow.f64",
44 "expf32" => "llvm.exp.f32",
45 "expf64" => "llvm.exp.f64",
46 "exp2f32" => "llvm.exp2.f32",
47 "exp2f64" => "llvm.exp2.f64",
48 "logf32" => "llvm.log.f32",
49 "logf64" => "llvm.log.f64",
50 "log10f32" => "llvm.log10.f32",
51 "log10f64" => "llvm.log10.f64",
52 "log2f32" => "llvm.log2.f32",
53 "log2f64" => "llvm.log2.f64",
54 "fmaf32" => "llvm.fma.f32",
55 "fmaf64" => "llvm.fma.f64",
56 "fabsf32" => "llvm.fabs.f32",
57 "fabsf64" => "llvm.fabs.f64",
58 "copysignf32" => "llvm.copysign.f32",
59 "copysignf64" => "llvm.copysign.f64",
60 "floorf32" => "llvm.floor.f32",
61 "floorf64" => "llvm.floor.f64",
62 "ceilf32" => "llvm.ceil.f32",
63 "ceilf64" => "llvm.ceil.f64",
64 "truncf32" => "llvm.trunc.f32",
65 "truncf64" => "llvm.trunc.f64",
66 "rintf32" => "llvm.rint.f32",
67 "rintf64" => "llvm.rint.f64",
68 "nearbyintf32" => "llvm.nearbyint.f32",
69 "nearbyintf64" => "llvm.nearbyint.f64",
70 "roundf32" => "llvm.round.f32",
71 "roundf64" => "llvm.round.f64",
72 "assume" => "llvm.assume",
73 "abort" => "llvm.trap",
76 Some(cx.get_intrinsic(&llvm_name))
79 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
80 fn codegen_intrinsic_call(
83 fn_ty: &FnType<'tcx, Ty<'tcx>>,
84 args: &[OperandRef<'tcx, &'ll Value>],
90 let (def_id, substs) = match callee_ty.sty {
91 ty::FnDef(def_id, substs) => (def_id, substs),
92 _ => bug!("expected fn item type, found {}", callee_ty)
95 let sig = callee_ty.fn_sig(tcx);
96 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
97 let arg_tys = sig.inputs();
98 let ret_ty = sig.output();
99 let name = &*tcx.item_name(def_id).as_str();
101 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
102 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align.abi);
104 let simple = get_simple_intrinsic(self, name);
105 let llval = match name {
106 _ if simple.is_some() => {
107 self.call(simple.unwrap(),
108 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
115 let expect = self.get_intrinsic(&("llvm.expect.i1"));
116 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
119 let expect = self.get_intrinsic(&("llvm.expect.i1"));
120 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
131 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
132 self.call(llfn, &[], None)
135 let tp_ty = substs.type_at(0);
136 self.const_usize(self.size_of(tp_ty).bytes())
139 self.va_start(args[0].immediate())
142 self.va_end(args[0].immediate())
145 let va_list = match (tcx.lang_items().va_list(), &result.layout.ty.sty) {
146 (Some(did), ty::Adt(def, _)) if def.did == did => args[0].immediate(),
147 (Some(_), _) => self.load(args[0].immediate(),
148 tcx.data_layout.pointer_align.abi),
149 (None, _) => bug!("`va_list` language item must be defined")
151 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
152 self.call(intrinsic, &[llresult, va_list], None);
156 match fn_ty.ret.layout.abi {
157 layout::Abi::Scalar(ref scalar) => {
159 Primitive::Int(..) => {
160 if self.cx().size_of(ret_ty).bytes() < 4 {
161 // va_arg should not be called on a integer type
162 // less than 4 bytes in length. If it is, promote
163 // the integer to a `i32` and truncate the result
164 // back to the smaller type.
165 let promoted_result = emit_va_arg(self, args[0],
167 self.trunc(promoted_result, llret_ty)
169 emit_va_arg(self, args[0], ret_ty)
172 Primitive::Float(FloatTy::F64) |
173 Primitive::Pointer => {
174 emit_va_arg(self, args[0], ret_ty)
176 // `va_arg` should never be used with the return type f32.
177 Primitive::Float(FloatTy::F32) => {
178 bug!("the va_arg intrinsic does not work with `f32`")
183 bug!("the va_arg intrinsic does not work with non-scalar types")
188 let tp_ty = substs.type_at(0);
189 if let OperandValue::Pair(_, meta) = args[0].val {
190 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
193 self.const_usize(self.size_of(tp_ty).bytes())
197 let tp_ty = substs.type_at(0);
198 self.const_usize(self.align_of(tp_ty).bytes())
200 "min_align_of_val" => {
201 let tp_ty = substs.type_at(0);
202 if let OperandValue::Pair(_, meta) = args[0].val {
203 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
206 self.const_usize(self.align_of(tp_ty).bytes())
210 let tp_ty = substs.type_at(0);
211 self.const_usize(self.layout_of(tp_ty).align.pref.bytes())
214 let tp_ty = substs.type_at(0);
215 let ty_name = self.tcx.type_name(tp_ty);
216 OperandRef::from_const(self, ty_name).immediate_or_packed_pair(self)
219 self.const_u64(self.tcx.type_id_hash(substs.type_at(0)))
222 let ty = substs.type_at(0);
223 if !self.layout_of(ty).is_zst() {
224 // Just zero out the stack slot.
225 // If we store a zero constant, LLVM will drown in vreg allocation for large
226 // data structures, and the generated code will be awful. (A telltale sign of
227 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
239 // Effectively no-ops
240 "uninit" | "forget" => {
244 let tp_ty = substs.type_at(0);
246 self.const_bool(self.type_needs_drop(tp_ty))
249 let ptr = args[0].immediate();
250 let offset = args[1].immediate();
251 self.inbounds_gep(ptr, &[offset])
254 let ptr = args[0].immediate();
255 let offset = args[1].immediate();
256 self.gep(ptr, &[offset])
259 "copy_nonoverlapping" => {
260 copy_intrinsic(self, false, false, substs.type_at(0),
261 args[1].immediate(), args[0].immediate(), args[2].immediate());
265 copy_intrinsic(self, true, false, substs.type_at(0),
266 args[1].immediate(), args[0].immediate(), args[2].immediate());
270 memset_intrinsic(self, false, substs.type_at(0),
271 args[0].immediate(), args[1].immediate(), args[2].immediate());
275 "volatile_copy_nonoverlapping_memory" => {
276 copy_intrinsic(self, false, true, substs.type_at(0),
277 args[0].immediate(), args[1].immediate(), args[2].immediate());
280 "volatile_copy_memory" => {
281 copy_intrinsic(self, true, true, substs.type_at(0),
282 args[0].immediate(), args[1].immediate(), args[2].immediate());
285 "volatile_set_memory" => {
286 memset_intrinsic(self, true, substs.type_at(0),
287 args[0].immediate(), args[1].immediate(), args[2].immediate());
290 "volatile_load" | "unaligned_volatile_load" => {
291 let tp_ty = substs.type_at(0);
292 let mut ptr = args[0].immediate();
293 if let PassMode::Cast(ty) = fn_ty.ret.mode {
294 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
296 let load = self.volatile_load(ptr);
297 let align = if name == "unaligned_volatile_load" {
300 self.align_of(tp_ty).bytes() as u32
303 llvm::LLVMSetAlignment(load, align);
305 to_immediate(self, load, self.layout_of(tp_ty))
307 "volatile_store" => {
308 let dst = args[0].deref(self.cx());
309 args[1].val.volatile_store(self, dst);
312 "unaligned_volatile_store" => {
313 let dst = args[0].deref(self.cx());
314 args[1].val.unaligned_volatile_store(self, dst);
317 "prefetch_read_data" | "prefetch_write_data" |
318 "prefetch_read_instruction" | "prefetch_write_instruction" => {
319 let expect = self.get_intrinsic(&("llvm.prefetch"));
320 let (rw, cache_type) = match name {
321 "prefetch_read_data" => (0, 1),
322 "prefetch_write_data" => (1, 1),
323 "prefetch_read_instruction" => (0, 0),
324 "prefetch_write_instruction" => (1, 0),
331 self.const_i32(cache_type)
334 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
335 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
336 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
337 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" |
338 "unchecked_add" | "unchecked_sub" | "unchecked_mul" | "exact_div" |
339 "rotate_left" | "rotate_right" | "saturating_add" | "saturating_sub" => {
341 match int_type_width_signed(ty, self) {
342 Some((width, signed)) =>
345 let y = self.const_bool(false);
346 let llfn = self.get_intrinsic(
347 &format!("llvm.{}.i{}", name, width),
349 self.call(llfn, &[args[0].immediate(), y], None)
351 "ctlz_nonzero" | "cttz_nonzero" => {
352 let y = self.const_bool(true);
353 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
354 let llfn = self.get_intrinsic(llvm_name);
355 self.call(llfn, &[args[0].immediate(), y], None)
357 "ctpop" => self.call(
358 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
359 &[args[0].immediate()],
364 args[0].immediate() // byte swap a u8/i8 is just a no-op
368 &format!("llvm.bswap.i{}", width),
370 &[args[0].immediate()],
378 &format!("llvm.bitreverse.i{}", width),
380 &[args[0].immediate()],
384 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
385 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
386 if signed { 's' } else { 'u' },
388 let llfn = self.get_intrinsic(&intrinsic);
390 // Convert `i1` to a `bool`, and write it to the out parameter
391 let pair = self.call(llfn, &[
395 let val = self.extract_value(pair, 0);
396 let overflow = self.extract_value(pair, 1);
397 let overflow = self.zext(overflow, self.type_bool());
399 let dest = result.project_field(self, 0);
400 self.store(val, dest.llval, dest.align);
401 let dest = result.project_field(self, 1);
402 self.store(overflow, dest.llval, dest.align);
406 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
407 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
408 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
411 self.exactsdiv(args[0].immediate(), args[1].immediate())
413 self.exactudiv(args[0].immediate(), args[1].immediate())
417 self.sdiv(args[0].immediate(), args[1].immediate())
419 self.udiv(args[0].immediate(), args[1].immediate())
423 self.srem(args[0].immediate(), args[1].immediate())
425 self.urem(args[0].immediate(), args[1].immediate())
427 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
430 self.ashr(args[0].immediate(), args[1].immediate())
432 self.lshr(args[0].immediate(), args[1].immediate())
436 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
438 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
443 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
445 self.unchecked_usub(args[0].immediate(), args[1].immediate())
450 self.unchecked_smul(args[0].immediate(), args[1].immediate())
452 self.unchecked_umul(args[0].immediate(), args[1].immediate())
455 "rotate_left" | "rotate_right" => {
456 let is_left = name == "rotate_left";
457 let val = args[0].immediate();
458 let raw_shift = args[1].immediate();
459 if llvm_util::get_major_version() >= 7 {
460 // rotate = funnel shift with first two args the same
461 let llvm_name = &format!("llvm.fsh{}.i{}",
462 if is_left { 'l' } else { 'r' }, width);
463 let llfn = self.get_intrinsic(llvm_name);
464 self.call(llfn, &[val, val, raw_shift], None)
466 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
467 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
468 let width = self.const_uint(
472 let shift = self.urem(raw_shift, width);
473 let width_minus_raw_shift = self.sub(width, raw_shift);
474 let inv_shift = self.urem(width_minus_raw_shift, width);
475 let shift1 = self.shl(
477 if is_left { shift } else { inv_shift },
479 let shift2 = self.lshr(
481 if !is_left { shift } else { inv_shift },
483 self.or(shift1, shift2)
486 "saturating_add" | "saturating_sub" => {
487 let is_add = name == "saturating_add";
488 let lhs = args[0].immediate();
489 let rhs = args[1].immediate();
490 if llvm_util::get_major_version() >= 8 {
491 let llvm_name = &format!("llvm.{}{}.sat.i{}",
492 if signed { 's' } else { 'u' },
493 if is_add { "add" } else { "sub" },
495 let llfn = self.get_intrinsic(llvm_name);
496 self.call(llfn, &[lhs, rhs], None)
498 let llvm_name = &format!("llvm.{}{}.with.overflow.i{}",
499 if signed { 's' } else { 'u' },
500 if is_add { "add" } else { "sub" },
502 let llfn = self.get_intrinsic(llvm_name);
503 let pair = self.call(llfn, &[lhs, rhs], None);
504 let val = self.extract_value(pair, 0);
505 let overflow = self.extract_value(pair, 1);
506 let llty = self.type_ix(width);
508 let limit = if signed {
509 let limit_lo = self.const_uint_big(
510 llty, (i128::MIN >> (128 - width)) as u128);
511 let limit_hi = self.const_uint_big(
512 llty, (i128::MAX >> (128 - width)) as u128);
514 IntPredicate::IntSLT, val, self.const_uint(llty, 0));
515 self.select(neg, limit_hi, limit_lo)
517 self.const_uint_big(llty, u128::MAX >> (128 - width))
519 self.const_uint(llty, 0)
521 self.select(overflow, limit, val)
527 span_invalid_monomorphization_error(
529 &format!("invalid monomorphization of `{}` intrinsic: \
530 expected basic integer type, found `{}`", name, ty));
536 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
537 match float_type_width(arg_tys[0]) {
540 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
541 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
542 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
543 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
544 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
548 span_invalid_monomorphization_error(
550 &format!("invalid monomorphization of `{}` intrinsic: \
551 expected basic float type, found `{}`", name, arg_tys[0]));
558 "discriminant_value" => {
559 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
562 name if name.starts_with("simd_") => {
563 match generic_simd_intrinsic(self, name,
572 // This requires that atomic intrinsics follow a specific naming pattern:
573 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
574 name if name.starts_with("atomic_") => {
575 use rustc_codegen_ssa::common::AtomicOrdering::*;
576 use rustc_codegen_ssa::common::
577 {SynchronizationScope, AtomicRmwBinOp};
579 let split: Vec<&str> = name.split('_').collect();
581 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
582 let (order, failorder) = match split.len() {
583 2 => (SequentiallyConsistent, SequentiallyConsistent),
584 3 => match split[2] {
585 "unordered" => (Unordered, Unordered),
586 "relaxed" => (Monotonic, Monotonic),
587 "acq" => (Acquire, Acquire),
588 "rel" => (Release, Monotonic),
589 "acqrel" => (AcquireRelease, Acquire),
590 "failrelaxed" if is_cxchg =>
591 (SequentiallyConsistent, Monotonic),
592 "failacq" if is_cxchg =>
593 (SequentiallyConsistent, Acquire),
594 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
596 4 => match (split[2], split[3]) {
597 ("acq", "failrelaxed") if is_cxchg =>
598 (Acquire, Monotonic),
599 ("acqrel", "failrelaxed") if is_cxchg =>
600 (AcquireRelease, Monotonic),
601 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
603 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
606 let invalid_monomorphization = |ty| {
607 span_invalid_monomorphization_error(tcx.sess, span,
608 &format!("invalid monomorphization of `{}` intrinsic: \
609 expected basic integer type, found `{}`", name, ty));
613 "cxchg" | "cxchgweak" => {
614 let ty = substs.type_at(0);
615 if int_type_width_signed(ty, self).is_some() {
616 let weak = split[1] == "cxchgweak";
617 let pair = self.atomic_cmpxchg(
624 let val = self.extract_value(pair, 0);
625 let success = self.extract_value(pair, 1);
626 let success = self.zext(success, self.type_bool());
628 let dest = result.project_field(self, 0);
629 self.store(val, dest.llval, dest.align);
630 let dest = result.project_field(self, 1);
631 self.store(success, dest.llval, dest.align);
634 return invalid_monomorphization(ty);
639 let ty = substs.type_at(0);
640 if int_type_width_signed(ty, self).is_some() {
641 let size = self.size_of(ty);
642 self.atomic_load(args[0].immediate(), order, size)
644 return invalid_monomorphization(ty);
649 let ty = substs.type_at(0);
650 if int_type_width_signed(ty, self).is_some() {
651 let size = self.size_of(ty);
660 return invalid_monomorphization(ty);
665 self.atomic_fence(order, SynchronizationScope::CrossThread);
669 "singlethreadfence" => {
670 self.atomic_fence(order, SynchronizationScope::SingleThread);
674 // These are all AtomicRMW ops
676 let atom_op = match op {
677 "xchg" => AtomicRmwBinOp::AtomicXchg,
678 "xadd" => AtomicRmwBinOp::AtomicAdd,
679 "xsub" => AtomicRmwBinOp::AtomicSub,
680 "and" => AtomicRmwBinOp::AtomicAnd,
681 "nand" => AtomicRmwBinOp::AtomicNand,
682 "or" => AtomicRmwBinOp::AtomicOr,
683 "xor" => AtomicRmwBinOp::AtomicXor,
684 "max" => AtomicRmwBinOp::AtomicMax,
685 "min" => AtomicRmwBinOp::AtomicMin,
686 "umax" => AtomicRmwBinOp::AtomicUMax,
687 "umin" => AtomicRmwBinOp::AtomicUMin,
688 _ => self.sess().fatal("unknown atomic operation")
691 let ty = substs.type_at(0);
692 if int_type_width_signed(ty, self).is_some() {
700 return invalid_monomorphization(ty);
706 "nontemporal_store" => {
707 let dst = args[0].deref(self.cx());
708 args[1].val.nontemporal_store(self, dst);
712 _ => bug!("unknown intrinsic '{}'", name),
715 if !fn_ty.ret.is_ignore() {
716 if let PassMode::Cast(ty) = fn_ty.ret.mode {
717 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
718 let ptr = self.pointercast(result.llval, ptr_llty);
719 self.store(llval, ptr, result.align);
721 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
722 .val.store(self, result);
727 fn abort(&mut self) {
728 let fnname = self.get_intrinsic(&("llvm.trap"));
729 self.call(fnname, &[], None);
732 fn assume(&mut self, val: Self::Value) {
733 let assume_intrinsic = self.get_intrinsic("llvm.assume");
734 self.call(assume_intrinsic, &[val], None);
737 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
738 let expect = self.get_intrinsic(&"llvm.expect.i1");
739 self.call(expect, &[cond, self.const_bool(expected)], None)
742 fn va_start(&mut self, list: &'ll Value) -> &'ll Value {
743 let target = &self.cx.tcx.sess.target.target;
744 let arch = &target.arch;
745 // A pointer to the architecture specific structure is passed to this
746 // function. For pointer variants (i686, RISC-V, Windows, etc), we
747 // should do do nothing, as the address to the pointer is needed. For
748 // architectures with a architecture specific structure (`Aarch64`,
749 // `X86_64`, etc), this function should load the structure from the
751 let va_list = match &**arch {
752 _ if target.options.is_like_windows => list,
753 "aarch64" if target.target_os == "ios" => list,
754 "aarch64" | "x86_64" | "powerpc" =>
755 self.load(list, self.tcx().data_layout.pointer_align.abi),
758 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
759 self.call(intrinsic, &[va_list], None)
762 fn va_end(&mut self, list: &'ll Value) -> &'ll Value {
763 let target = &self.cx.tcx.sess.target.target;
764 let arch = &target.arch;
765 // See the comment in `va_start` for the purpose of the following.
766 let va_list = match &**arch {
767 _ if target.options.is_like_windows => list,
768 "aarch64" if target.target_os == "ios" => list,
769 "aarch64" | "x86_64" | "powerpc" =>
770 self.load(list, self.tcx().data_layout.pointer_align.abi),
773 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
774 self.call(intrinsic, &[va_list], None)
779 bx: &mut Builder<'a, 'll, 'tcx>,
787 let (size, align) = bx.size_and_align_of(ty);
788 let size = bx.mul(bx.const_usize(size.bytes()), count);
789 let flags = if volatile {
795 bx.memmove(dst, align, src, align, size, flags);
797 bx.memcpy(dst, align, src, align, size, flags);
802 bx: &mut Builder<'a, 'll, 'tcx>,
809 let (size, align) = bx.size_and_align_of(ty);
810 let size = bx.mul(bx.const_usize(size.bytes()), count);
811 let flags = if volatile {
816 bx.memset(dst, val, size, align, flags);
820 bx: &mut Builder<'a, 'll, 'tcx>,
823 local_ptr: &'ll Value,
826 if bx.sess().no_landing_pads() {
827 bx.call(func, &[data], None);
828 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
829 bx.store(bx.const_null(bx.type_i8p()), dest, ptr_align);
830 } else if wants_msvc_seh(bx.sess()) {
831 codegen_msvc_try(bx, func, data, local_ptr, dest);
833 codegen_gnu_try(bx, func, data, local_ptr, dest);
837 // MSVC's definition of the `rust_try` function.
839 // This implementation uses the new exception handling instructions in LLVM
840 // which have support in LLVM for SEH on MSVC targets. Although these
841 // instructions are meant to work for all targets, as of the time of this
842 // writing, however, LLVM does not recommend the usage of these new instructions
843 // as the old ones are still more optimized.
845 bx: &mut Builder<'a, 'll, 'tcx>,
848 local_ptr: &'ll Value,
851 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
852 bx.set_personality_fn(bx.eh_personality());
854 let mut normal = bx.build_sibling_block("normal");
855 let mut catchswitch = bx.build_sibling_block("catchswitch");
856 let mut catchpad = bx.build_sibling_block("catchpad");
857 let mut caught = bx.build_sibling_block("caught");
859 let func = llvm::get_param(bx.llfn(), 0);
860 let data = llvm::get_param(bx.llfn(), 1);
861 let local_ptr = llvm::get_param(bx.llfn(), 2);
863 // We're generating an IR snippet that looks like:
865 // declare i32 @rust_try(%func, %data, %ptr) {
866 // %slot = alloca i64*
867 // invoke %func(%data) to label %normal unwind label %catchswitch
873 // %cs = catchswitch within none [%catchpad] unwind to caller
876 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
877 // %ptr[0] = %slot[0]
878 // %ptr[1] = %slot[1]
879 // catchret from %tok to label %caught
885 // This structure follows the basic usage of throw/try/catch in LLVM.
886 // For example, compile this C++ snippet to see what LLVM generates:
888 // #include <stdint.h>
890 // int bar(void (*foo)(void), uint64_t *ret) {
894 // } catch(uint64_t a[2]) {
901 // More information can be found in libstd's seh.rs implementation.
902 let i64p = bx.type_ptr_to(bx.type_i64());
903 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
904 let slot = bx.alloca(i64p, "slot", ptr_align);
905 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
907 normal.ret(bx.const_i32(0));
909 let cs = catchswitch.catch_switch(None, None, 1);
910 catchswitch.add_handler(cs, catchpad.llbb());
912 let tydesc = match bx.tcx().lang_items().msvc_try_filter() {
913 Some(did) => bx.get_static(did),
914 None => bug!("msvc_try_filter not defined"),
916 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.const_i32(0), slot]);
917 let addr = catchpad.load(slot, ptr_align);
919 let i64_align = bx.tcx().data_layout.i64_align.abi;
920 let arg1 = catchpad.load(addr, i64_align);
921 let val1 = bx.const_i32(1);
922 let gep1 = catchpad.inbounds_gep(addr, &[val1]);
923 let arg2 = catchpad.load(gep1, i64_align);
924 let local_ptr = catchpad.bitcast(local_ptr, i64p);
925 let gep2 = catchpad.inbounds_gep(local_ptr, &[val1]);
926 catchpad.store(arg1, local_ptr, i64_align);
927 catchpad.store(arg2, gep2, i64_align);
928 catchpad.catch_ret(&funclet, caught.llbb());
930 caught.ret(bx.const_i32(1));
933 // Note that no invoke is used here because by definition this function
934 // can't panic (that's what it's catching).
935 let ret = bx.call(llfn, &[func, data, local_ptr], None);
936 let i32_align = bx.tcx().data_layout.i32_align.abi;
937 bx.store(ret, dest, i32_align);
940 // Definition of the standard "try" function for Rust using the GNU-like model
941 // of exceptions (e.g., the normal semantics of LLVM's landingpad and invoke
944 // This codegen is a little surprising because we always call a shim
945 // function instead of inlining the call to `invoke` manually here. This is done
946 // because in LLVM we're only allowed to have one personality per function
947 // definition. The call to the `try` intrinsic is being inlined into the
948 // function calling it, and that function may already have other personality
949 // functions in play. By calling a shim we're guaranteed that our shim will have
950 // the right personality function.
952 bx: &mut Builder<'a, 'll, 'tcx>,
955 local_ptr: &'ll Value,
958 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
959 // Codegens the shims described above:
962 // invoke %func(%args...) normal %normal unwind %catch
968 // (ptr, _) = landingpad
969 // store ptr, %local_ptr
972 // Note that the `local_ptr` data passed into the `try` intrinsic is
973 // expected to be `*mut *mut u8` for this to actually work, but that's
974 // managed by the standard library.
976 let mut then = bx.build_sibling_block("then");
977 let mut catch = bx.build_sibling_block("catch");
979 let func = llvm::get_param(bx.llfn(), 0);
980 let data = llvm::get_param(bx.llfn(), 1);
981 let local_ptr = llvm::get_param(bx.llfn(), 2);
982 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
983 then.ret(bx.const_i32(0));
985 // Type indicator for the exception being thrown.
987 // The first value in this tuple is a pointer to the exception object
988 // being thrown. The second value is a "selector" indicating which of
989 // the landing pad clauses the exception's type had been matched to.
990 // rust_try ignores the selector.
991 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
992 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
993 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
994 let ptr = catch.extract_value(vals, 0);
995 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
996 let bitcast = catch.bitcast(local_ptr, bx.type_ptr_to(bx.type_i8p()));
997 catch.store(ptr, bitcast, ptr_align);
998 catch.ret(bx.const_i32(1));
1001 // Note that no invoke is used here because by definition this function
1002 // can't panic (that's what it's catching).
1003 let ret = bx.call(llfn, &[func, data, local_ptr], None);
1004 let i32_align = bx.tcx().data_layout.i32_align.abi;
1005 bx.store(ret, dest, i32_align);
1008 // Helper function to give a Block to a closure to codegen a shim function.
1009 // This is currently primarily used for the `try` intrinsic functions above.
1010 fn gen_fn<'ll, 'tcx>(
1011 cx: &CodegenCx<'ll, 'tcx>,
1013 inputs: Vec<Ty<'tcx>>,
1015 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1017 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1021 hir::Unsafety::Unsafe,
1024 let llfn = cx.define_internal_fn(name, rust_fn_sig);
1025 attributes::from_fn_attrs(cx, llfn, None, rust_fn_sig);
1026 let bx = Builder::new_block(cx, llfn, "entry-block");
1031 // Helper function used to get a handle to the `__rust_try` function used to
1032 // catch exceptions.
1034 // This function is only generated once and is then cached.
1035 fn get_rust_try_fn<'ll, 'tcx>(
1036 cx: &CodegenCx<'ll, 'tcx>,
1037 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1039 if let Some(llfn) = cx.rust_try_fn.get() {
1043 // Define the type up front for the signature of the rust_try function.
1045 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1046 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1050 hir::Unsafety::Unsafe,
1053 let output = tcx.types.i32;
1054 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1055 cx.rust_try_fn.set(Some(rust_try));
1059 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1060 span_err!(a, b, E0511, "{}", c);
1063 fn generic_simd_intrinsic(
1064 bx: &mut Builder<'a, 'll, 'tcx>,
1066 callee_ty: Ty<'tcx>,
1067 args: &[OperandRef<'tcx, &'ll Value>],
1069 llret_ty: &'ll Type,
1071 ) -> Result<&'ll Value, ()> {
1072 // macros for error handling:
1073 macro_rules! emit_error {
1077 ($msg: tt, $($fmt: tt)*) => {
1078 span_invalid_monomorphization_error(
1080 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1085 macro_rules! return_error {
1088 emit_error!($($fmt)*);
1094 macro_rules! require {
1095 ($cond: expr, $($fmt: tt)*) => {
1097 return_error!($($fmt)*);
1102 macro_rules! require_simd {
1103 ($ty: expr, $position: expr) => {
1104 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1109 let sig = tcx.normalize_erasing_late_bound_regions(
1110 ty::ParamEnv::reveal_all(),
1111 &callee_ty.fn_sig(tcx),
1113 let arg_tys = sig.inputs();
1115 if name == "simd_select_bitmask" {
1116 let in_ty = arg_tys[0];
1117 let m_len = match in_ty.sty {
1118 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1119 // of intentional as there's not currently a use case for that.
1120 ty::Int(i) => i.bit_width().unwrap(),
1121 ty::Uint(i) => i.bit_width().unwrap(),
1122 _ => return_error!("`{}` is not an integral type", in_ty),
1124 require_simd!(arg_tys[1], "argument");
1125 let v_len = arg_tys[1].simd_size(tcx);
1126 require!(m_len == v_len,
1127 "mismatched lengths: mask length `{}` != other vector length `{}`",
1130 let i1 = bx.type_i1();
1131 let i1xn = bx.type_vector(i1, m_len as u64);
1132 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1133 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1136 // every intrinsic below takes a SIMD vector as its first argument
1137 require_simd!(arg_tys[0], "input");
1138 let in_ty = arg_tys[0];
1139 let in_elem = arg_tys[0].simd_type(tcx);
1140 let in_len = arg_tys[0].simd_size(tcx);
1142 let comparison = match name {
1143 "simd_eq" => Some(hir::BinOpKind::Eq),
1144 "simd_ne" => Some(hir::BinOpKind::Ne),
1145 "simd_lt" => Some(hir::BinOpKind::Lt),
1146 "simd_le" => Some(hir::BinOpKind::Le),
1147 "simd_gt" => Some(hir::BinOpKind::Gt),
1148 "simd_ge" => Some(hir::BinOpKind::Ge),
1152 if let Some(cmp_op) = comparison {
1153 require_simd!(ret_ty, "return");
1155 let out_len = ret_ty.simd_size(tcx);
1156 require!(in_len == out_len,
1157 "expected return type with length {} (same as input type `{}`), \
1158 found `{}` with length {}",
1161 require!(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1162 "expected return type with integer elements, found `{}` with non-integer `{}`",
1164 ret_ty.simd_type(tcx));
1166 return Ok(compare_simd_types(bx,
1167 args[0].immediate(),
1168 args[1].immediate(),
1174 if name.starts_with("simd_shuffle") {
1175 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1176 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1178 require_simd!(ret_ty, "return");
1180 let out_len = ret_ty.simd_size(tcx);
1181 require!(out_len == n,
1182 "expected return type of length {}, found `{}` with length {}",
1183 n, ret_ty, out_len);
1184 require!(in_elem == ret_ty.simd_type(tcx),
1185 "expected return element type `{}` (element of input `{}`), \
1186 found `{}` with element type `{}`",
1188 ret_ty, ret_ty.simd_type(tcx));
1190 let total_len = in_len as u128 * 2;
1192 let vector = args[2].immediate();
1194 let indices: Option<Vec<_>> = (0..n)
1197 let val = bx.const_get_elt(vector, i as u64);
1198 match bx.const_to_opt_u128(val, true) {
1200 emit_error!("shuffle index #{} is not a constant", arg_idx);
1203 Some(idx) if idx >= total_len => {
1204 emit_error!("shuffle index #{} is out of bounds (limit {})",
1205 arg_idx, total_len);
1208 Some(idx) => Some(bx.const_i32(idx as i32)),
1212 let indices = match indices {
1214 None => return Ok(bx.const_null(llret_ty))
1217 return Ok(bx.shuffle_vector(args[0].immediate(),
1218 args[1].immediate(),
1219 bx.const_vector(&indices)))
1222 if name == "simd_insert" {
1223 require!(in_elem == arg_tys[2],
1224 "expected inserted type `{}` (element of input `{}`), found `{}`",
1225 in_elem, in_ty, arg_tys[2]);
1226 return Ok(bx.insert_element(args[0].immediate(),
1227 args[2].immediate(),
1228 args[1].immediate()))
1230 if name == "simd_extract" {
1231 require!(ret_ty == in_elem,
1232 "expected return type `{}` (element of input `{}`), found `{}`",
1233 in_elem, in_ty, ret_ty);
1234 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1237 if name == "simd_select" {
1238 let m_elem_ty = in_elem;
1240 require_simd!(arg_tys[1], "argument");
1241 let v_len = arg_tys[1].simd_size(tcx);
1242 require!(m_len == v_len,
1243 "mismatched lengths: mask length `{}` != other vector length `{}`",
1246 match m_elem_ty.sty {
1248 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1250 // truncate the mask to a vector of i1s
1251 let i1 = bx.type_i1();
1252 let i1xn = bx.type_vector(i1, m_len as u64);
1253 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1254 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1257 if name == "simd_bitmask" {
1258 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1259 // vector mask and returns an unsigned integer containing the most
1260 // significant bit (MSB) of each lane.
1261 use rustc_target::abi::HasDataLayout;
1263 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1265 let expected_int_bits = in_len.max(8);
1267 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1269 "bitmask `{}`, expected `u{}`",
1270 ret_ty, expected_int_bits
1274 // Integer vector <i{in_bitwidth} x in_len>:
1275 let (i_xn, in_elem_bitwidth) = match in_elem.sty {
1277 args[0].immediate(),
1278 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1281 args[0].immediate(),
1282 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1285 "vector argument `{}`'s element type `{}`, expected integer element type",
1290 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1291 let shift_indices = vec![
1292 bx.cx.const_int(bx.type_ix(in_elem_bitwidth as _), (in_elem_bitwidth - 1) as _); in_len
1294 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1295 // Truncate vector to an <i1 x N>
1296 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len as _));
1297 // Bitcast <i1 x N> to iN:
1298 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len as _));
1299 // Zero-extend iN to the bitmask type:
1300 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits as _)));
1303 fn simd_simple_float_intrinsic(
1305 in_elem: &::rustc::ty::TyS<'_>,
1306 in_ty: &::rustc::ty::TyS<'_>,
1308 bx: &mut Builder<'a, 'll, 'tcx>,
1310 args: &[OperandRef<'tcx, &'ll Value>],
1311 ) -> Result<&'ll Value, ()> {
1312 macro_rules! emit_error {
1316 ($msg: tt, $($fmt: tt)*) => {
1317 span_invalid_monomorphization_error(
1319 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1323 macro_rules! return_error {
1326 emit_error!($($fmt)*);
1331 let ety = match in_elem.sty {
1332 ty::Float(f) if f.bit_width() == 32 => {
1333 if in_len < 2 || in_len > 16 {
1335 "unsupported floating-point vector `{}` with length `{}` \
1336 out-of-range [2, 16]",
1341 ty::Float(f) if f.bit_width() == 64 => {
1342 if in_len < 2 || in_len > 8 {
1343 return_error!("unsupported floating-point vector `{}` with length `{}` \
1344 out-of-range [2, 8]",
1350 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1354 return_error!("`{}` is not a floating-point type", in_ty);
1358 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1359 let intrinsic = bx.get_intrinsic(&llvm_name);
1360 let c = bx.call(intrinsic,
1361 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1363 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1369 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1372 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1375 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1378 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1381 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1384 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1387 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1390 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1393 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1396 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1399 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1402 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1405 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1408 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1410 _ => { /* fallthrough */ }
1414 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1415 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1416 fn llvm_vector_str(elem_ty: ty::Ty<'_>, vec_len: usize, no_pointers: usize) -> String {
1417 let p0s: String = "p0".repeat(no_pointers);
1419 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1420 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1421 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1422 _ => unreachable!(),
1426 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty<'_>, vec_len: usize,
1427 mut no_pointers: usize) -> &'ll Type {
1428 // FIXME: use cx.layout_of(ty).llvm_type() ?
1429 let mut elem_ty = match elem_ty.sty {
1430 ty::Int(v) => cx.type_int_from_ty( v),
1431 ty::Uint(v) => cx.type_uint_from_ty( v),
1432 ty::Float(v) => cx.type_float_from_ty( v),
1433 _ => unreachable!(),
1435 while no_pointers > 0 {
1436 elem_ty = cx.type_ptr_to(elem_ty);
1439 cx.type_vector(elem_ty, vec_len as u64)
1443 if name == "simd_gather" {
1444 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1445 // mask: <N x i{M}>) -> <N x T>
1446 // * N: number of elements in the input vectors
1447 // * T: type of the element to load
1448 // * M: any integer width is supported, will be truncated to i1
1450 // All types must be simd vector types
1451 require_simd!(in_ty, "first");
1452 require_simd!(arg_tys[1], "second");
1453 require_simd!(arg_tys[2], "third");
1454 require_simd!(ret_ty, "return");
1456 // Of the same length:
1457 require!(in_len == arg_tys[1].simd_size(tcx),
1458 "expected {} argument with length {} (same as input type `{}`), \
1459 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1460 arg_tys[1].simd_size(tcx));
1461 require!(in_len == arg_tys[2].simd_size(tcx),
1462 "expected {} argument with length {} (same as input type `{}`), \
1463 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1464 arg_tys[2].simd_size(tcx));
1466 // The return type must match the first argument type
1467 require!(ret_ty == in_ty,
1468 "expected return type `{}`, found `{}`",
1471 // This counts how many pointers
1472 fn ptr_count(t: ty::Ty<'_>) -> usize {
1474 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1480 fn non_ptr(t: ty::Ty<'_>) -> ty::Ty<'_> {
1482 ty::RawPtr(p) => non_ptr(p.ty),
1487 // The second argument must be a simd vector with an element type that's a pointer
1488 // to the element type of the first argument
1489 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1490 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1491 non_ptr(arg_tys[1].simd_type(tcx))),
1493 require!(false, "expected element type `{}` of second argument `{}` \
1494 to be a pointer to the element type `{}` of the first \
1495 argument `{}`, found `{}` != `*_ {}`",
1496 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1497 arg_tys[1].simd_type(tcx), in_elem);
1501 assert!(pointer_count > 0);
1502 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1503 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1505 // The element type of the third argument must be a signed integer type of any width:
1506 match arg_tys[2].simd_type(tcx).sty {
1509 require!(false, "expected element type `{}` of third argument `{}` \
1510 to be a signed integer type",
1511 arg_tys[2].simd_type(tcx), arg_tys[2]);
1515 // Alignment of T, must be a constant integer value:
1516 let alignment_ty = bx.type_i32();
1517 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1519 // Truncate the mask vector to a vector of i1s:
1520 let (mask, mask_ty) = {
1521 let i1 = bx.type_i1();
1522 let i1xn = bx.type_vector(i1, in_len as u64);
1523 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1526 // Type of the vector of pointers:
1527 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1528 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1530 // Type of the vector of elements:
1531 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1532 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1534 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1535 llvm_elem_vec_str, llvm_pointer_vec_str);
1536 let f = bx.declare_cfn(&llvm_intrinsic,
1538 llvm_pointer_vec_ty,
1541 llvm_elem_vec_ty], llvm_elem_vec_ty));
1542 llvm::SetUnnamedAddr(f, false);
1543 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1548 if name == "simd_scatter" {
1549 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1550 // mask: <N x i{M}>) -> ()
1551 // * N: number of elements in the input vectors
1552 // * T: type of the element to load
1553 // * M: any integer width is supported, will be truncated to i1
1555 // All types must be simd vector types
1556 require_simd!(in_ty, "first");
1557 require_simd!(arg_tys[1], "second");
1558 require_simd!(arg_tys[2], "third");
1560 // Of the same length:
1561 require!(in_len == arg_tys[1].simd_size(tcx),
1562 "expected {} argument with length {} (same as input type `{}`), \
1563 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1564 arg_tys[1].simd_size(tcx));
1565 require!(in_len == arg_tys[2].simd_size(tcx),
1566 "expected {} argument with length {} (same as input type `{}`), \
1567 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1568 arg_tys[2].simd_size(tcx));
1570 // This counts how many pointers
1571 fn ptr_count(t: ty::Ty<'_>) -> usize {
1573 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1579 fn non_ptr(t: ty::Ty<'_>) -> ty::Ty<'_> {
1581 ty::RawPtr(p) => non_ptr(p.ty),
1586 // The second argument must be a simd vector with an element type that's a pointer
1587 // to the element type of the first argument
1588 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1589 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1590 => (ptr_count(arg_tys[1].simd_type(tcx)),
1591 non_ptr(arg_tys[1].simd_type(tcx))),
1593 require!(false, "expected element type `{}` of second argument `{}` \
1594 to be a pointer to the element type `{}` of the first \
1595 argument `{}`, found `{}` != `*mut {}`",
1596 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1597 arg_tys[1].simd_type(tcx), in_elem);
1601 assert!(pointer_count > 0);
1602 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1603 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1605 // The element type of the third argument must be a signed integer type of any width:
1606 match arg_tys[2].simd_type(tcx).sty {
1609 require!(false, "expected element type `{}` of third argument `{}` \
1610 to be a signed integer type",
1611 arg_tys[2].simd_type(tcx), arg_tys[2]);
1615 // Alignment of T, must be a constant integer value:
1616 let alignment_ty = bx.type_i32();
1617 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1619 // Truncate the mask vector to a vector of i1s:
1620 let (mask, mask_ty) = {
1621 let i1 = bx.type_i1();
1622 let i1xn = bx.type_vector(i1, in_len as u64);
1623 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1626 let ret_t = bx.type_void();
1628 // Type of the vector of pointers:
1629 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1630 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1632 // Type of the vector of elements:
1633 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1634 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1636 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1637 llvm_elem_vec_str, llvm_pointer_vec_str);
1638 let f = bx.declare_cfn(&llvm_intrinsic,
1639 bx.type_func(&[llvm_elem_vec_ty,
1640 llvm_pointer_vec_ty,
1643 llvm::SetUnnamedAddr(f, false);
1644 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1649 macro_rules! arith_red {
1650 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1652 require!(ret_ty == in_elem,
1653 "expected return type `{}` (element of input `{}`), found `{}`",
1654 in_elem, in_ty, ret_ty);
1655 return match in_elem.sty {
1656 ty::Int(_) | ty::Uint(_) => {
1657 let r = bx.$integer_reduce(args[0].immediate());
1659 // if overflow occurs, the result is the
1660 // mathematical result modulo 2^n:
1661 if name.contains("mul") {
1662 Ok(bx.mul(args[1].immediate(), r))
1664 Ok(bx.add(args[1].immediate(), r))
1667 Ok(bx.$integer_reduce(args[0].immediate()))
1671 // ordered arithmetic reductions take an accumulator
1672 let acc = if $ordered {
1673 let acc = args[1].immediate();
1674 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1675 // * if the accumulator of the fadd isn't 0, incorrect
1676 // code is generated
1677 // * if the accumulator of the fmul isn't 1, incorrect
1678 // code is generated
1679 match bx.const_get_real(acc) {
1680 None => return_error!("accumulator of {} is not a constant", $name),
1681 Some((v, loses_info)) => {
1682 if $name.contains("mul") && v != 1.0_f64 {
1683 return_error!("accumulator of {} is not 1.0", $name);
1684 } else if $name.contains("add") && v != 0.0_f64 {
1685 return_error!("accumulator of {} is not 0.0", $name);
1686 } else if loses_info {
1687 return_error!("accumulator of {} loses information", $name);
1693 // unordered arithmetic reductions do not:
1694 match f.bit_width() {
1695 32 => bx.const_undef(bx.type_f32()),
1696 64 => bx.const_undef(bx.type_f64()),
1699 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1700 $name, in_ty, in_elem, v, ret_ty
1705 Ok(bx.$float_reduce(acc, args[0].immediate()))
1709 "unsupported {} from `{}` with element `{}` to `{}`",
1710 $name, in_ty, in_elem, ret_ty
1718 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1719 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1720 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1721 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1723 macro_rules! minmax_red {
1724 ($name:tt: $int_red:ident, $float_red:ident) => {
1726 require!(ret_ty == in_elem,
1727 "expected return type `{}` (element of input `{}`), found `{}`",
1728 in_elem, in_ty, ret_ty);
1729 return match in_elem.sty {
1731 Ok(bx.$int_red(args[0].immediate(), true))
1734 Ok(bx.$int_red(args[0].immediate(), false))
1737 Ok(bx.$float_red(args[0].immediate()))
1740 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1741 $name, in_ty, in_elem, ret_ty)
1749 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1750 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1752 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1753 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1755 macro_rules! bitwise_red {
1756 ($name:tt : $red:ident, $boolean:expr) => {
1758 let input = if !$boolean {
1759 require!(ret_ty == in_elem,
1760 "expected return type `{}` (element of input `{}`), found `{}`",
1761 in_elem, in_ty, ret_ty);
1765 ty::Int(_) | ty::Uint(_) => {},
1767 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1768 $name, in_ty, in_elem, ret_ty)
1772 // boolean reductions operate on vectors of i1s:
1773 let i1 = bx.type_i1();
1774 let i1xn = bx.type_vector(i1, in_len as u64);
1775 bx.trunc(args[0].immediate(), i1xn)
1777 return match in_elem.sty {
1778 ty::Int(_) | ty::Uint(_) => {
1779 let r = bx.$red(input);
1784 bx.zext(r, bx.type_bool())
1789 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1790 $name, in_ty, in_elem, ret_ty)
1797 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1798 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1799 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1800 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1801 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1803 if name == "simd_cast" {
1804 require_simd!(ret_ty, "return");
1805 let out_len = ret_ty.simd_size(tcx);
1806 require!(in_len == out_len,
1807 "expected return type with length {} (same as input type `{}`), \
1808 found `{}` with length {}",
1811 // casting cares about nominal type, not just structural type
1812 let out_elem = ret_ty.simd_type(tcx);
1814 if in_elem == out_elem { return Ok(args[0].immediate()); }
1816 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1818 let (in_style, in_width) = match in_elem.sty {
1819 // vectors of pointer-sized integers should've been
1820 // disallowed before here, so this unwrap is safe.
1821 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1822 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1823 ty::Float(f) => (Style::Float, f.bit_width()),
1824 _ => (Style::Unsupported, 0)
1826 let (out_style, out_width) = match out_elem.sty {
1827 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1828 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1829 ty::Float(f) => (Style::Float, f.bit_width()),
1830 _ => (Style::Unsupported, 0)
1833 match (in_style, out_style) {
1834 (Style::Int(in_is_signed), Style::Int(_)) => {
1835 return Ok(match in_width.cmp(&out_width) {
1836 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1837 Ordering::Equal => args[0].immediate(),
1838 Ordering::Less => if in_is_signed {
1839 bx.sext(args[0].immediate(), llret_ty)
1841 bx.zext(args[0].immediate(), llret_ty)
1845 (Style::Int(in_is_signed), Style::Float) => {
1846 return Ok(if in_is_signed {
1847 bx.sitofp(args[0].immediate(), llret_ty)
1849 bx.uitofp(args[0].immediate(), llret_ty)
1852 (Style::Float, Style::Int(out_is_signed)) => {
1853 return Ok(if out_is_signed {
1854 bx.fptosi(args[0].immediate(), llret_ty)
1856 bx.fptoui(args[0].immediate(), llret_ty)
1859 (Style::Float, Style::Float) => {
1860 return Ok(match in_width.cmp(&out_width) {
1861 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1862 Ordering::Equal => args[0].immediate(),
1863 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1866 _ => {/* Unsupported. Fallthrough. */}
1869 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1873 macro_rules! arith {
1874 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1875 $(if name == stringify!($name) {
1877 $($(ty::$p(_))|* => {
1878 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1883 "unsupported operation on `{}` with element `{}`",
1890 simd_add: Uint, Int => add, Float => fadd;
1891 simd_sub: Uint, Int => sub, Float => fsub;
1892 simd_mul: Uint, Int => mul, Float => fmul;
1893 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1894 simd_rem: Uint => urem, Int => srem, Float => frem;
1895 simd_shl: Uint, Int => shl;
1896 simd_shr: Uint => lshr, Int => ashr;
1897 simd_and: Uint, Int => and;
1898 simd_or: Uint, Int => or;
1899 simd_xor: Uint, Int => xor;
1900 simd_fmax: Float => maxnum;
1901 simd_fmin: Float => minnum;
1905 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
1906 let lhs = args[0].immediate();
1907 let rhs = args[1].immediate();
1908 let is_add = name == "simd_saturating_add";
1909 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1910 let (signed, elem_width, elem_ty) = match in_elem.sty {
1914 i.bit_width().unwrap_or(ptr_bits),
1915 bx.cx.type_int_from_ty(i)
1920 i.bit_width().unwrap_or(ptr_bits),
1921 bx.cx.type_uint_from_ty(i)
1925 "expected element type `{}` of vector type `{}` \
1926 to be a signed or unsigned integer type",
1927 arg_tys[0].simd_type(tcx), arg_tys[0]
1931 let llvm_intrinsic = &format!(
1932 "llvm.{}{}.sat.v{}i{}",
1933 if signed { 's' } else { 'u' },
1934 if is_add { "add" } else { "sub" },
1937 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1939 let f = bx.declare_cfn(
1941 bx.type_func(&[vec_ty, vec_ty], vec_ty)
1943 llvm::SetUnnamedAddr(f, false);
1944 let v = bx.call(f, &[lhs, rhs], None);
1948 span_bug!(span, "unknown SIMD intrinsic");
1951 // Returns the width of an int Ty, and if it's signed or not
1952 // Returns None if the type is not an integer
1953 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1955 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1957 ty::Int(t) => Some((match t {
1958 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1959 ast::IntTy::I8 => 8,
1960 ast::IntTy::I16 => 16,
1961 ast::IntTy::I32 => 32,
1962 ast::IntTy::I64 => 64,
1963 ast::IntTy::I128 => 128,
1965 ty::Uint(t) => Some((match t {
1966 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1967 ast::UintTy::U8 => 8,
1968 ast::UintTy::U16 => 16,
1969 ast::UintTy::U32 => 32,
1970 ast::UintTy::U64 => 64,
1971 ast::UintTy::U128 => 128,
1977 // Returns the width of a float Ty
1978 // Returns None if the type is not a float
1979 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
1981 ty::Float(t) => Some(t.bit_width() as u64),