4 use crate::abi::{Abi, FnType, LlvmType, PassMode};
5 use crate::context::CodegenCx;
6 use crate::type_::Type;
7 use crate::type_of::LayoutLlvmExt;
8 use crate::builder::Builder;
9 use crate::value::Value;
10 use crate::va_arg::emit_va_arg;
11 use rustc_codegen_ssa::MemFlags;
12 use rustc_codegen_ssa::mir::place::PlaceRef;
13 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
14 use rustc_codegen_ssa::glue;
15 use rustc_codegen_ssa::base::{to_immediate, wants_msvc_seh, compare_simd_types};
16 use rustc::ty::{self, Ty};
17 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, Primitive};
18 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
20 use syntax::ast::{self, FloatTy};
22 use rustc_codegen_ssa::traits::*;
24 use rustc::session::Session;
27 use std::cmp::Ordering;
28 use std::{iter, i128, u128};
30 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
31 let llvm_name = match name {
32 "sqrtf32" => "llvm.sqrt.f32",
33 "sqrtf64" => "llvm.sqrt.f64",
34 "powif32" => "llvm.powi.f32",
35 "powif64" => "llvm.powi.f64",
36 "sinf32" => "llvm.sin.f32",
37 "sinf64" => "llvm.sin.f64",
38 "cosf32" => "llvm.cos.f32",
39 "cosf64" => "llvm.cos.f64",
40 "powf32" => "llvm.pow.f32",
41 "powf64" => "llvm.pow.f64",
42 "expf32" => "llvm.exp.f32",
43 "expf64" => "llvm.exp.f64",
44 "exp2f32" => "llvm.exp2.f32",
45 "exp2f64" => "llvm.exp2.f64",
46 "logf32" => "llvm.log.f32",
47 "logf64" => "llvm.log.f64",
48 "log10f32" => "llvm.log10.f32",
49 "log10f64" => "llvm.log10.f64",
50 "log2f32" => "llvm.log2.f32",
51 "log2f64" => "llvm.log2.f64",
52 "fmaf32" => "llvm.fma.f32",
53 "fmaf64" => "llvm.fma.f64",
54 "fabsf32" => "llvm.fabs.f32",
55 "fabsf64" => "llvm.fabs.f64",
56 "minnumf32" => "llvm.minnum.f32",
57 "minnumf64" => "llvm.minnum.f64",
58 "maxnumf32" => "llvm.maxnum.f32",
59 "maxnumf64" => "llvm.maxnum.f64",
60 "copysignf32" => "llvm.copysign.f32",
61 "copysignf64" => "llvm.copysign.f64",
62 "floorf32" => "llvm.floor.f32",
63 "floorf64" => "llvm.floor.f64",
64 "ceilf32" => "llvm.ceil.f32",
65 "ceilf64" => "llvm.ceil.f64",
66 "truncf32" => "llvm.trunc.f32",
67 "truncf64" => "llvm.trunc.f64",
68 "rintf32" => "llvm.rint.f32",
69 "rintf64" => "llvm.rint.f64",
70 "nearbyintf32" => "llvm.nearbyint.f32",
71 "nearbyintf64" => "llvm.nearbyint.f64",
72 "roundf32" => "llvm.round.f32",
73 "roundf64" => "llvm.round.f64",
74 "assume" => "llvm.assume",
75 "abort" => "llvm.trap",
78 Some(cx.get_intrinsic(&llvm_name))
81 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
82 fn codegen_intrinsic_call(
85 fn_ty: &FnType<'tcx, Ty<'tcx>>,
86 args: &[OperandRef<'tcx, &'ll Value>],
92 let (def_id, substs) = match callee_ty.sty {
93 ty::FnDef(def_id, substs) => (def_id, substs),
94 _ => bug!("expected fn item type, found {}", callee_ty)
97 let sig = callee_ty.fn_sig(tcx);
98 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
99 let arg_tys = sig.inputs();
100 let ret_ty = sig.output();
101 let name = &*tcx.item_name(def_id).as_str();
103 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
104 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align.abi);
106 let simple = get_simple_intrinsic(self, name);
107 let llval = match name {
108 _ if simple.is_some() => {
109 self.call(simple.unwrap(),
110 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
117 let expect = self.get_intrinsic(&("llvm.expect.i1"));
118 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
121 let expect = self.get_intrinsic(&("llvm.expect.i1"));
122 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
133 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
134 self.call(llfn, &[], None)
137 let tp_ty = substs.type_at(0);
138 self.const_usize(self.size_of(tp_ty).bytes())
141 self.va_start(args[0].immediate())
144 self.va_end(args[0].immediate())
147 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
148 self.call(intrinsic, &[args[0].immediate(), args[1].immediate()], None)
151 match fn_ty.ret.layout.abi {
152 layout::Abi::Scalar(ref scalar) => {
154 Primitive::Int(..) => {
155 if self.cx().size_of(ret_ty).bytes() < 4 {
156 // va_arg should not be called on a integer type
157 // less than 4 bytes in length. If it is, promote
158 // the integer to a `i32` and truncate the result
159 // back to the smaller type.
160 let promoted_result = emit_va_arg(self, args[0],
162 self.trunc(promoted_result, llret_ty)
164 emit_va_arg(self, args[0], ret_ty)
167 Primitive::Float(FloatTy::F64) |
168 Primitive::Pointer => {
169 emit_va_arg(self, args[0], ret_ty)
171 // `va_arg` should never be used with the return type f32.
172 Primitive::Float(FloatTy::F32) => {
173 bug!("the va_arg intrinsic does not work with `f32`")
178 bug!("the va_arg intrinsic does not work with non-scalar types")
183 let tp_ty = substs.type_at(0);
184 if let OperandValue::Pair(_, meta) = args[0].val {
185 let (llsize, _) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
188 self.const_usize(self.size_of(tp_ty).bytes())
192 let tp_ty = substs.type_at(0);
193 self.const_usize(self.align_of(tp_ty).bytes())
195 "min_align_of_val" => {
196 let tp_ty = substs.type_at(0);
197 if let OperandValue::Pair(_, meta) = args[0].val {
198 let (_, llalign) = glue::size_and_align_of_dst(self, tp_ty, Some(meta));
201 self.const_usize(self.align_of(tp_ty).bytes())
205 let tp_ty = substs.type_at(0);
206 self.const_usize(self.layout_of(tp_ty).align.pref.bytes())
209 let tp_ty = substs.type_at(0);
210 let ty_name = self.tcx.type_name(tp_ty);
211 OperandRef::from_const(self, ty_name).immediate_or_packed_pair(self)
214 self.const_u64(self.tcx.type_id_hash(substs.type_at(0)))
217 let ty = substs.type_at(0);
218 if !self.layout_of(ty).is_zst() {
219 // Just zero out the stack slot.
220 // If we store a zero constant, LLVM will drown in vreg allocation for large
221 // data structures, and the generated code will be awful. (A telltale sign of
222 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
234 // Effectively no-ops
239 let tp_ty = substs.type_at(0);
241 self.const_bool(self.type_needs_drop(tp_ty))
244 let ptr = args[0].immediate();
245 let offset = args[1].immediate();
246 self.inbounds_gep(ptr, &[offset])
249 let ptr = args[0].immediate();
250 let offset = args[1].immediate();
251 self.gep(ptr, &[offset])
254 "copy_nonoverlapping" => {
255 copy_intrinsic(self, false, false, substs.type_at(0),
256 args[1].immediate(), args[0].immediate(), args[2].immediate());
260 copy_intrinsic(self, true, false, substs.type_at(0),
261 args[1].immediate(), args[0].immediate(), args[2].immediate());
265 memset_intrinsic(self, false, substs.type_at(0),
266 args[0].immediate(), args[1].immediate(), args[2].immediate());
270 "volatile_copy_nonoverlapping_memory" => {
271 copy_intrinsic(self, false, true, substs.type_at(0),
272 args[0].immediate(), args[1].immediate(), args[2].immediate());
275 "volatile_copy_memory" => {
276 copy_intrinsic(self, true, true, substs.type_at(0),
277 args[0].immediate(), args[1].immediate(), args[2].immediate());
280 "volatile_set_memory" => {
281 memset_intrinsic(self, true, substs.type_at(0),
282 args[0].immediate(), args[1].immediate(), args[2].immediate());
285 "volatile_load" | "unaligned_volatile_load" => {
286 let tp_ty = substs.type_at(0);
287 let mut ptr = args[0].immediate();
288 if let PassMode::Cast(ty) = fn_ty.ret.mode {
289 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
291 let load = self.volatile_load(ptr);
292 let align = if name == "unaligned_volatile_load" {
295 self.align_of(tp_ty).bytes() as u32
298 llvm::LLVMSetAlignment(load, align);
300 to_immediate(self, load, self.layout_of(tp_ty))
302 "volatile_store" => {
303 let dst = args[0].deref(self.cx());
304 args[1].val.volatile_store(self, dst);
307 "unaligned_volatile_store" => {
308 let dst = args[0].deref(self.cx());
309 args[1].val.unaligned_volatile_store(self, dst);
312 "prefetch_read_data" | "prefetch_write_data" |
313 "prefetch_read_instruction" | "prefetch_write_instruction" => {
314 let expect = self.get_intrinsic(&("llvm.prefetch"));
315 let (rw, cache_type) = match name {
316 "prefetch_read_data" => (0, 1),
317 "prefetch_write_data" => (1, 1),
318 "prefetch_read_instruction" => (0, 0),
319 "prefetch_write_instruction" => (1, 0),
326 self.const_i32(cache_type)
329 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
330 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
331 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
332 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" |
333 "unchecked_add" | "unchecked_sub" | "unchecked_mul" | "exact_div" |
334 "rotate_left" | "rotate_right" | "saturating_add" | "saturating_sub" => {
336 match int_type_width_signed(ty, self) {
337 Some((width, signed)) =>
340 let y = self.const_bool(false);
341 let llfn = self.get_intrinsic(
342 &format!("llvm.{}.i{}", name, width),
344 self.call(llfn, &[args[0].immediate(), y], None)
346 "ctlz_nonzero" | "cttz_nonzero" => {
347 let y = self.const_bool(true);
348 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
349 let llfn = self.get_intrinsic(llvm_name);
350 self.call(llfn, &[args[0].immediate(), y], None)
352 "ctpop" => self.call(
353 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
354 &[args[0].immediate()],
359 args[0].immediate() // byte swap a u8/i8 is just a no-op
363 &format!("llvm.bswap.i{}", width),
365 &[args[0].immediate()],
373 &format!("llvm.bitreverse.i{}", width),
375 &[args[0].immediate()],
379 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
380 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
381 if signed { 's' } else { 'u' },
383 let llfn = self.get_intrinsic(&intrinsic);
385 // Convert `i1` to a `bool`, and write it to the out parameter
386 let pair = self.call(llfn, &[
390 let val = self.extract_value(pair, 0);
391 let overflow = self.extract_value(pair, 1);
392 let overflow = self.zext(overflow, self.type_bool());
394 let dest = result.project_field(self, 0);
395 self.store(val, dest.llval, dest.align);
396 let dest = result.project_field(self, 1);
397 self.store(overflow, dest.llval, dest.align);
401 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
402 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
403 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
406 self.exactsdiv(args[0].immediate(), args[1].immediate())
408 self.exactudiv(args[0].immediate(), args[1].immediate())
412 self.sdiv(args[0].immediate(), args[1].immediate())
414 self.udiv(args[0].immediate(), args[1].immediate())
418 self.srem(args[0].immediate(), args[1].immediate())
420 self.urem(args[0].immediate(), args[1].immediate())
422 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
425 self.ashr(args[0].immediate(), args[1].immediate())
427 self.lshr(args[0].immediate(), args[1].immediate())
431 self.unchecked_sadd(args[0].immediate(), args[1].immediate())
433 self.unchecked_uadd(args[0].immediate(), args[1].immediate())
438 self.unchecked_ssub(args[0].immediate(), args[1].immediate())
440 self.unchecked_usub(args[0].immediate(), args[1].immediate())
445 self.unchecked_smul(args[0].immediate(), args[1].immediate())
447 self.unchecked_umul(args[0].immediate(), args[1].immediate())
450 "rotate_left" | "rotate_right" => {
451 let is_left = name == "rotate_left";
452 let val = args[0].immediate();
453 let raw_shift = args[1].immediate();
454 if llvm_util::get_major_version() >= 7 {
455 // rotate = funnel shift with first two args the same
456 let llvm_name = &format!("llvm.fsh{}.i{}",
457 if is_left { 'l' } else { 'r' }, width);
458 let llfn = self.get_intrinsic(llvm_name);
459 self.call(llfn, &[val, val, raw_shift], None)
461 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
462 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
463 let width = self.const_uint(
467 let shift = self.urem(raw_shift, width);
468 let width_minus_raw_shift = self.sub(width, raw_shift);
469 let inv_shift = self.urem(width_minus_raw_shift, width);
470 let shift1 = self.shl(
472 if is_left { shift } else { inv_shift },
474 let shift2 = self.lshr(
476 if !is_left { shift } else { inv_shift },
478 self.or(shift1, shift2)
481 "saturating_add" | "saturating_sub" => {
482 let is_add = name == "saturating_add";
483 let lhs = args[0].immediate();
484 let rhs = args[1].immediate();
485 if llvm_util::get_major_version() >= 8 {
486 let llvm_name = &format!("llvm.{}{}.sat.i{}",
487 if signed { 's' } else { 'u' },
488 if is_add { "add" } else { "sub" },
490 let llfn = self.get_intrinsic(llvm_name);
491 self.call(llfn, &[lhs, rhs], None)
493 let llvm_name = &format!("llvm.{}{}.with.overflow.i{}",
494 if signed { 's' } else { 'u' },
495 if is_add { "add" } else { "sub" },
497 let llfn = self.get_intrinsic(llvm_name);
498 let pair = self.call(llfn, &[lhs, rhs], None);
499 let val = self.extract_value(pair, 0);
500 let overflow = self.extract_value(pair, 1);
501 let llty = self.type_ix(width);
503 let limit = if signed {
504 let limit_lo = self.const_uint_big(
505 llty, (i128::MIN >> (128 - width)) as u128);
506 let limit_hi = self.const_uint_big(
507 llty, (i128::MAX >> (128 - width)) as u128);
509 IntPredicate::IntSLT, val, self.const_uint(llty, 0));
510 self.select(neg, limit_hi, limit_lo)
512 self.const_uint_big(llty, u128::MAX >> (128 - width))
514 self.const_uint(llty, 0)
516 self.select(overflow, limit, val)
522 span_invalid_monomorphization_error(
524 &format!("invalid monomorphization of `{}` intrinsic: \
525 expected basic integer type, found `{}`", name, ty));
531 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
532 match float_type_width(arg_tys[0]) {
535 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
536 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
537 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
538 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
539 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
543 span_invalid_monomorphization_error(
545 &format!("invalid monomorphization of `{}` intrinsic: \
546 expected basic float type, found `{}`", name, arg_tys[0]));
553 "discriminant_value" => {
554 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
557 name if name.starts_with("simd_") => {
558 match generic_simd_intrinsic(self, name,
567 // This requires that atomic intrinsics follow a specific naming pattern:
568 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
569 name if name.starts_with("atomic_") => {
570 use rustc_codegen_ssa::common::AtomicOrdering::*;
571 use rustc_codegen_ssa::common::
572 {SynchronizationScope, AtomicRmwBinOp};
574 let split: Vec<&str> = name.split('_').collect();
576 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
577 let (order, failorder) = match split.len() {
578 2 => (SequentiallyConsistent, SequentiallyConsistent),
579 3 => match split[2] {
580 "unordered" => (Unordered, Unordered),
581 "relaxed" => (Monotonic, Monotonic),
582 "acq" => (Acquire, Acquire),
583 "rel" => (Release, Monotonic),
584 "acqrel" => (AcquireRelease, Acquire),
585 "failrelaxed" if is_cxchg =>
586 (SequentiallyConsistent, Monotonic),
587 "failacq" if is_cxchg =>
588 (SequentiallyConsistent, Acquire),
589 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
591 4 => match (split[2], split[3]) {
592 ("acq", "failrelaxed") if is_cxchg =>
593 (Acquire, Monotonic),
594 ("acqrel", "failrelaxed") if is_cxchg =>
595 (AcquireRelease, Monotonic),
596 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
598 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
601 let invalid_monomorphization = |ty| {
602 span_invalid_monomorphization_error(tcx.sess, span,
603 &format!("invalid monomorphization of `{}` intrinsic: \
604 expected basic integer type, found `{}`", name, ty));
608 "cxchg" | "cxchgweak" => {
609 let ty = substs.type_at(0);
610 if int_type_width_signed(ty, self).is_some() {
611 let weak = split[1] == "cxchgweak";
612 let pair = self.atomic_cmpxchg(
619 let val = self.extract_value(pair, 0);
620 let success = self.extract_value(pair, 1);
621 let success = self.zext(success, self.type_bool());
623 let dest = result.project_field(self, 0);
624 self.store(val, dest.llval, dest.align);
625 let dest = result.project_field(self, 1);
626 self.store(success, dest.llval, dest.align);
629 return invalid_monomorphization(ty);
634 let ty = substs.type_at(0);
635 if int_type_width_signed(ty, self).is_some() {
636 let size = self.size_of(ty);
637 self.atomic_load(args[0].immediate(), order, size)
639 return invalid_monomorphization(ty);
644 let ty = substs.type_at(0);
645 if int_type_width_signed(ty, self).is_some() {
646 let size = self.size_of(ty);
655 return invalid_monomorphization(ty);
660 self.atomic_fence(order, SynchronizationScope::CrossThread);
664 "singlethreadfence" => {
665 self.atomic_fence(order, SynchronizationScope::SingleThread);
669 // These are all AtomicRMW ops
671 let atom_op = match op {
672 "xchg" => AtomicRmwBinOp::AtomicXchg,
673 "xadd" => AtomicRmwBinOp::AtomicAdd,
674 "xsub" => AtomicRmwBinOp::AtomicSub,
675 "and" => AtomicRmwBinOp::AtomicAnd,
676 "nand" => AtomicRmwBinOp::AtomicNand,
677 "or" => AtomicRmwBinOp::AtomicOr,
678 "xor" => AtomicRmwBinOp::AtomicXor,
679 "max" => AtomicRmwBinOp::AtomicMax,
680 "min" => AtomicRmwBinOp::AtomicMin,
681 "umax" => AtomicRmwBinOp::AtomicUMax,
682 "umin" => AtomicRmwBinOp::AtomicUMin,
683 _ => self.sess().fatal("unknown atomic operation")
686 let ty = substs.type_at(0);
687 if int_type_width_signed(ty, self).is_some() {
695 return invalid_monomorphization(ty);
701 "nontemporal_store" => {
702 let dst = args[0].deref(self.cx());
703 args[1].val.nontemporal_store(self, dst);
707 _ => bug!("unknown intrinsic '{}'", name),
710 if !fn_ty.ret.is_ignore() {
711 if let PassMode::Cast(ty) = fn_ty.ret.mode {
712 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
713 let ptr = self.pointercast(result.llval, ptr_llty);
714 self.store(llval, ptr, result.align);
716 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
717 .val.store(self, result);
722 fn abort(&mut self) {
723 let fnname = self.get_intrinsic(&("llvm.trap"));
724 self.call(fnname, &[], None);
727 fn assume(&mut self, val: Self::Value) {
728 let assume_intrinsic = self.get_intrinsic("llvm.assume");
729 self.call(assume_intrinsic, &[val], None);
732 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
733 let expect = self.get_intrinsic(&"llvm.expect.i1");
734 self.call(expect, &[cond, self.const_bool(expected)], None)
737 fn va_start(&mut self, va_list: &'ll Value) -> &'ll Value {
738 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
739 self.call(intrinsic, &[va_list], None)
742 fn va_end(&mut self, va_list: &'ll Value) -> &'ll Value {
743 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
744 self.call(intrinsic, &[va_list], None)
749 bx: &mut Builder<'a, 'll, 'tcx>,
757 let (size, align) = bx.size_and_align_of(ty);
758 let size = bx.mul(bx.const_usize(size.bytes()), count);
759 let flags = if volatile {
765 bx.memmove(dst, align, src, align, size, flags);
767 bx.memcpy(dst, align, src, align, size, flags);
772 bx: &mut Builder<'a, 'll, 'tcx>,
779 let (size, align) = bx.size_and_align_of(ty);
780 let size = bx.mul(bx.const_usize(size.bytes()), count);
781 let flags = if volatile {
786 bx.memset(dst, val, size, align, flags);
790 bx: &mut Builder<'a, 'll, 'tcx>,
793 local_ptr: &'ll Value,
796 if bx.sess().no_landing_pads() {
797 bx.call(func, &[data], None);
798 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
799 bx.store(bx.const_null(bx.type_i8p()), dest, ptr_align);
800 } else if wants_msvc_seh(bx.sess()) {
801 codegen_msvc_try(bx, func, data, local_ptr, dest);
803 codegen_gnu_try(bx, func, data, local_ptr, dest);
807 // MSVC's definition of the `rust_try` function.
809 // This implementation uses the new exception handling instructions in LLVM
810 // which have support in LLVM for SEH on MSVC targets. Although these
811 // instructions are meant to work for all targets, as of the time of this
812 // writing, however, LLVM does not recommend the usage of these new instructions
813 // as the old ones are still more optimized.
815 bx: &mut Builder<'a, 'll, 'tcx>,
818 local_ptr: &'ll Value,
821 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
822 bx.set_personality_fn(bx.eh_personality());
824 let mut normal = bx.build_sibling_block("normal");
825 let mut catchswitch = bx.build_sibling_block("catchswitch");
826 let mut catchpad = bx.build_sibling_block("catchpad");
827 let mut caught = bx.build_sibling_block("caught");
829 let func = llvm::get_param(bx.llfn(), 0);
830 let data = llvm::get_param(bx.llfn(), 1);
831 let local_ptr = llvm::get_param(bx.llfn(), 2);
833 // We're generating an IR snippet that looks like:
835 // declare i32 @rust_try(%func, %data, %ptr) {
836 // %slot = alloca i64*
837 // invoke %func(%data) to label %normal unwind label %catchswitch
843 // %cs = catchswitch within none [%catchpad] unwind to caller
846 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
847 // %ptr[0] = %slot[0]
848 // %ptr[1] = %slot[1]
849 // catchret from %tok to label %caught
855 // This structure follows the basic usage of throw/try/catch in LLVM.
856 // For example, compile this C++ snippet to see what LLVM generates:
858 // #include <stdint.h>
860 // int bar(void (*foo)(void), uint64_t *ret) {
864 // } catch(uint64_t a[2]) {
871 // More information can be found in libstd's seh.rs implementation.
872 let i64p = bx.type_ptr_to(bx.type_i64());
873 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
874 let slot = bx.alloca(i64p, "slot", ptr_align);
875 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
877 normal.ret(bx.const_i32(0));
879 let cs = catchswitch.catch_switch(None, None, 1);
880 catchswitch.add_handler(cs, catchpad.llbb());
882 let tydesc = match bx.tcx().lang_items().msvc_try_filter() {
883 Some(did) => bx.get_static(did),
884 None => bug!("msvc_try_filter not defined"),
886 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.const_i32(0), slot]);
887 let addr = catchpad.load(slot, ptr_align);
889 let i64_align = bx.tcx().data_layout.i64_align.abi;
890 let arg1 = catchpad.load(addr, i64_align);
891 let val1 = bx.const_i32(1);
892 let gep1 = catchpad.inbounds_gep(addr, &[val1]);
893 let arg2 = catchpad.load(gep1, i64_align);
894 let local_ptr = catchpad.bitcast(local_ptr, i64p);
895 let gep2 = catchpad.inbounds_gep(local_ptr, &[val1]);
896 catchpad.store(arg1, local_ptr, i64_align);
897 catchpad.store(arg2, gep2, i64_align);
898 catchpad.catch_ret(&funclet, caught.llbb());
900 caught.ret(bx.const_i32(1));
903 // Note that no invoke is used here because by definition this function
904 // can't panic (that's what it's catching).
905 let ret = bx.call(llfn, &[func, data, local_ptr], None);
906 let i32_align = bx.tcx().data_layout.i32_align.abi;
907 bx.store(ret, dest, i32_align);
910 // Definition of the standard `try` function for Rust using the GNU-like model
911 // of exceptions (e.g., the normal semantics of LLVM's `landingpad` and `invoke`
914 // This codegen is a little surprising because we always call a shim
915 // function instead of inlining the call to `invoke` manually here. This is done
916 // because in LLVM we're only allowed to have one personality per function
917 // definition. The call to the `try` intrinsic is being inlined into the
918 // function calling it, and that function may already have other personality
919 // functions in play. By calling a shim we're guaranteed that our shim will have
920 // the right personality function.
922 bx: &mut Builder<'a, 'll, 'tcx>,
925 local_ptr: &'ll Value,
928 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
929 // Codegens the shims described above:
932 // invoke %func(%args...) normal %normal unwind %catch
938 // (ptr, _) = landingpad
939 // store ptr, %local_ptr
942 // Note that the `local_ptr` data passed into the `try` intrinsic is
943 // expected to be `*mut *mut u8` for this to actually work, but that's
944 // managed by the standard library.
946 let mut then = bx.build_sibling_block("then");
947 let mut catch = bx.build_sibling_block("catch");
949 let func = llvm::get_param(bx.llfn(), 0);
950 let data = llvm::get_param(bx.llfn(), 1);
951 let local_ptr = llvm::get_param(bx.llfn(), 2);
952 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
953 then.ret(bx.const_i32(0));
955 // Type indicator for the exception being thrown.
957 // The first value in this tuple is a pointer to the exception object
958 // being thrown. The second value is a "selector" indicating which of
959 // the landing pad clauses the exception's type had been matched to.
960 // rust_try ignores the selector.
961 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
962 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
963 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
964 let ptr = catch.extract_value(vals, 0);
965 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
966 let bitcast = catch.bitcast(local_ptr, bx.type_ptr_to(bx.type_i8p()));
967 catch.store(ptr, bitcast, ptr_align);
968 catch.ret(bx.const_i32(1));
971 // Note that no invoke is used here because by definition this function
972 // can't panic (that's what it's catching).
973 let ret = bx.call(llfn, &[func, data, local_ptr], None);
974 let i32_align = bx.tcx().data_layout.i32_align.abi;
975 bx.store(ret, dest, i32_align);
978 // Helper function to give a Block to a closure to codegen a shim function.
979 // This is currently primarily used for the `try` intrinsic functions above.
980 fn gen_fn<'ll, 'tcx>(
981 cx: &CodegenCx<'ll, 'tcx>,
983 inputs: Vec<Ty<'tcx>>,
985 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
987 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
991 hir::Unsafety::Unsafe,
994 let llfn = cx.define_internal_fn(name, rust_fn_sig);
995 attributes::from_fn_attrs(cx, llfn, None, rust_fn_sig);
996 let bx = Builder::new_block(cx, llfn, "entry-block");
1001 // Helper function used to get a handle to the `__rust_try` function used to
1002 // catch exceptions.
1004 // This function is only generated once and is then cached.
1005 fn get_rust_try_fn<'ll, 'tcx>(
1006 cx: &CodegenCx<'ll, 'tcx>,
1007 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1009 if let Some(llfn) = cx.rust_try_fn.get() {
1013 // Define the type up front for the signature of the rust_try function.
1015 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1016 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1020 hir::Unsafety::Unsafe,
1023 let output = tcx.types.i32;
1024 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1025 cx.rust_try_fn.set(Some(rust_try));
1029 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1030 span_err!(a, b, E0511, "{}", c);
1033 fn generic_simd_intrinsic(
1034 bx: &mut Builder<'a, 'll, 'tcx>,
1036 callee_ty: Ty<'tcx>,
1037 args: &[OperandRef<'tcx, &'ll Value>],
1039 llret_ty: &'ll Type,
1041 ) -> Result<&'ll Value, ()> {
1042 // macros for error handling:
1043 macro_rules! emit_error {
1047 ($msg: tt, $($fmt: tt)*) => {
1048 span_invalid_monomorphization_error(
1050 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1055 macro_rules! return_error {
1058 emit_error!($($fmt)*);
1064 macro_rules! require {
1065 ($cond: expr, $($fmt: tt)*) => {
1067 return_error!($($fmt)*);
1072 macro_rules! require_simd {
1073 ($ty: expr, $position: expr) => {
1074 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1079 let sig = tcx.normalize_erasing_late_bound_regions(
1080 ty::ParamEnv::reveal_all(),
1081 &callee_ty.fn_sig(tcx),
1083 let arg_tys = sig.inputs();
1085 if name == "simd_select_bitmask" {
1086 let in_ty = arg_tys[0];
1087 let m_len = match in_ty.sty {
1088 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1089 // of intentional as there's not currently a use case for that.
1090 ty::Int(i) => i.bit_width().unwrap(),
1091 ty::Uint(i) => i.bit_width().unwrap(),
1092 _ => return_error!("`{}` is not an integral type", in_ty),
1094 require_simd!(arg_tys[1], "argument");
1095 let v_len = arg_tys[1].simd_size(tcx);
1096 require!(m_len == v_len,
1097 "mismatched lengths: mask length `{}` != other vector length `{}`",
1100 let i1 = bx.type_i1();
1101 let i1xn = bx.type_vector(i1, m_len as u64);
1102 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1103 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1106 // every intrinsic below takes a SIMD vector as its first argument
1107 require_simd!(arg_tys[0], "input");
1108 let in_ty = arg_tys[0];
1109 let in_elem = arg_tys[0].simd_type(tcx);
1110 let in_len = arg_tys[0].simd_size(tcx);
1112 let comparison = match name {
1113 "simd_eq" => Some(hir::BinOpKind::Eq),
1114 "simd_ne" => Some(hir::BinOpKind::Ne),
1115 "simd_lt" => Some(hir::BinOpKind::Lt),
1116 "simd_le" => Some(hir::BinOpKind::Le),
1117 "simd_gt" => Some(hir::BinOpKind::Gt),
1118 "simd_ge" => Some(hir::BinOpKind::Ge),
1122 if let Some(cmp_op) = comparison {
1123 require_simd!(ret_ty, "return");
1125 let out_len = ret_ty.simd_size(tcx);
1126 require!(in_len == out_len,
1127 "expected return type with length {} (same as input type `{}`), \
1128 found `{}` with length {}",
1131 require!(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1132 "expected return type with integer elements, found `{}` with non-integer `{}`",
1134 ret_ty.simd_type(tcx));
1136 return Ok(compare_simd_types(bx,
1137 args[0].immediate(),
1138 args[1].immediate(),
1144 if name.starts_with("simd_shuffle") {
1145 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1146 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1148 require_simd!(ret_ty, "return");
1150 let out_len = ret_ty.simd_size(tcx);
1151 require!(out_len == n,
1152 "expected return type of length {}, found `{}` with length {}",
1153 n, ret_ty, out_len);
1154 require!(in_elem == ret_ty.simd_type(tcx),
1155 "expected return element type `{}` (element of input `{}`), \
1156 found `{}` with element type `{}`",
1158 ret_ty, ret_ty.simd_type(tcx));
1160 let total_len = in_len as u128 * 2;
1162 let vector = args[2].immediate();
1164 let indices: Option<Vec<_>> = (0..n)
1167 let val = bx.const_get_elt(vector, i as u64);
1168 match bx.const_to_opt_u128(val, true) {
1170 emit_error!("shuffle index #{} is not a constant", arg_idx);
1173 Some(idx) if idx >= total_len => {
1174 emit_error!("shuffle index #{} is out of bounds (limit {})",
1175 arg_idx, total_len);
1178 Some(idx) => Some(bx.const_i32(idx as i32)),
1182 let indices = match indices {
1184 None => return Ok(bx.const_null(llret_ty))
1187 return Ok(bx.shuffle_vector(args[0].immediate(),
1188 args[1].immediate(),
1189 bx.const_vector(&indices)))
1192 if name == "simd_insert" {
1193 require!(in_elem == arg_tys[2],
1194 "expected inserted type `{}` (element of input `{}`), found `{}`",
1195 in_elem, in_ty, arg_tys[2]);
1196 return Ok(bx.insert_element(args[0].immediate(),
1197 args[2].immediate(),
1198 args[1].immediate()))
1200 if name == "simd_extract" {
1201 require!(ret_ty == in_elem,
1202 "expected return type `{}` (element of input `{}`), found `{}`",
1203 in_elem, in_ty, ret_ty);
1204 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1207 if name == "simd_select" {
1208 let m_elem_ty = in_elem;
1210 require_simd!(arg_tys[1], "argument");
1211 let v_len = arg_tys[1].simd_size(tcx);
1212 require!(m_len == v_len,
1213 "mismatched lengths: mask length `{}` != other vector length `{}`",
1216 match m_elem_ty.sty {
1218 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1220 // truncate the mask to a vector of i1s
1221 let i1 = bx.type_i1();
1222 let i1xn = bx.type_vector(i1, m_len as u64);
1223 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1224 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1227 if name == "simd_bitmask" {
1228 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1229 // vector mask and returns an unsigned integer containing the most
1230 // significant bit (MSB) of each lane.
1231 use rustc_target::abi::HasDataLayout;
1233 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1235 let expected_int_bits = in_len.max(8);
1237 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1239 "bitmask `{}`, expected `u{}`",
1240 ret_ty, expected_int_bits
1244 // Integer vector <i{in_bitwidth} x in_len>:
1245 let (i_xn, in_elem_bitwidth) = match in_elem.sty {
1247 args[0].immediate(),
1248 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1251 args[0].immediate(),
1252 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1255 "vector argument `{}`'s element type `{}`, expected integer element type",
1260 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1261 let shift_indices = vec![
1262 bx.cx.const_int(bx.type_ix(in_elem_bitwidth as _), (in_elem_bitwidth - 1) as _); in_len
1264 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1265 // Truncate vector to an <i1 x N>
1266 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len as _));
1267 // Bitcast <i1 x N> to iN:
1268 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len as _));
1269 // Zero-extend iN to the bitmask type:
1270 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits as _)));
1273 fn simd_simple_float_intrinsic(
1275 in_elem: &::rustc::ty::TyS<'_>,
1276 in_ty: &::rustc::ty::TyS<'_>,
1278 bx: &mut Builder<'a, 'll, 'tcx>,
1280 args: &[OperandRef<'tcx, &'ll Value>],
1281 ) -> Result<&'ll Value, ()> {
1282 macro_rules! emit_error {
1286 ($msg: tt, $($fmt: tt)*) => {
1287 span_invalid_monomorphization_error(
1289 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1293 macro_rules! return_error {
1296 emit_error!($($fmt)*);
1301 let ety = match in_elem.sty {
1302 ty::Float(f) if f.bit_width() == 32 => {
1303 if in_len < 2 || in_len > 16 {
1305 "unsupported floating-point vector `{}` with length `{}` \
1306 out-of-range [2, 16]",
1311 ty::Float(f) if f.bit_width() == 64 => {
1312 if in_len < 2 || in_len > 8 {
1313 return_error!("unsupported floating-point vector `{}` with length `{}` \
1314 out-of-range [2, 8]",
1320 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1324 return_error!("`{}` is not a floating-point type", in_ty);
1328 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1329 let intrinsic = bx.get_intrinsic(&llvm_name);
1330 let c = bx.call(intrinsic,
1331 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1333 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1339 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1342 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1345 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1348 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1351 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1354 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1357 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1360 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1363 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1366 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1369 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1372 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1375 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1378 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1380 _ => { /* fallthrough */ }
1384 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1385 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1386 fn llvm_vector_str(elem_ty: Ty<'_>, vec_len: usize, no_pointers: usize) -> String {
1387 let p0s: String = "p0".repeat(no_pointers);
1389 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1390 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1391 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1392 _ => unreachable!(),
1396 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: usize,
1397 mut no_pointers: usize) -> &'ll Type {
1398 // FIXME: use cx.layout_of(ty).llvm_type() ?
1399 let mut elem_ty = match elem_ty.sty {
1400 ty::Int(v) => cx.type_int_from_ty( v),
1401 ty::Uint(v) => cx.type_uint_from_ty( v),
1402 ty::Float(v) => cx.type_float_from_ty( v),
1403 _ => unreachable!(),
1405 while no_pointers > 0 {
1406 elem_ty = cx.type_ptr_to(elem_ty);
1409 cx.type_vector(elem_ty, vec_len as u64)
1413 if name == "simd_gather" {
1414 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1415 // mask: <N x i{M}>) -> <N x T>
1416 // * N: number of elements in the input vectors
1417 // * T: type of the element to load
1418 // * M: any integer width is supported, will be truncated to i1
1420 // All types must be simd vector types
1421 require_simd!(in_ty, "first");
1422 require_simd!(arg_tys[1], "second");
1423 require_simd!(arg_tys[2], "third");
1424 require_simd!(ret_ty, "return");
1426 // Of the same length:
1427 require!(in_len == arg_tys[1].simd_size(tcx),
1428 "expected {} argument with length {} (same as input type `{}`), \
1429 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1430 arg_tys[1].simd_size(tcx));
1431 require!(in_len == arg_tys[2].simd_size(tcx),
1432 "expected {} argument with length {} (same as input type `{}`), \
1433 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1434 arg_tys[2].simd_size(tcx));
1436 // The return type must match the first argument type
1437 require!(ret_ty == in_ty,
1438 "expected return type `{}`, found `{}`",
1441 // This counts how many pointers
1442 fn ptr_count(t: Ty<'_>) -> usize {
1444 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1450 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1452 ty::RawPtr(p) => non_ptr(p.ty),
1457 // The second argument must be a simd vector with an element type that's a pointer
1458 // to the element type of the first argument
1459 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1460 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1461 non_ptr(arg_tys[1].simd_type(tcx))),
1463 require!(false, "expected element type `{}` of second argument `{}` \
1464 to be a pointer to the element type `{}` of the first \
1465 argument `{}`, found `{}` != `*_ {}`",
1466 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1467 arg_tys[1].simd_type(tcx), in_elem);
1471 assert!(pointer_count > 0);
1472 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1473 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1475 // The element type of the third argument must be a signed integer type of any width:
1476 match arg_tys[2].simd_type(tcx).sty {
1479 require!(false, "expected element type `{}` of third argument `{}` \
1480 to be a signed integer type",
1481 arg_tys[2].simd_type(tcx), arg_tys[2]);
1485 // Alignment of T, must be a constant integer value:
1486 let alignment_ty = bx.type_i32();
1487 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1489 // Truncate the mask vector to a vector of i1s:
1490 let (mask, mask_ty) = {
1491 let i1 = bx.type_i1();
1492 let i1xn = bx.type_vector(i1, in_len as u64);
1493 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1496 // Type of the vector of pointers:
1497 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1498 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1500 // Type of the vector of elements:
1501 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1502 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1504 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1505 llvm_elem_vec_str, llvm_pointer_vec_str);
1506 let f = bx.declare_cfn(&llvm_intrinsic,
1508 llvm_pointer_vec_ty,
1511 llvm_elem_vec_ty], llvm_elem_vec_ty));
1512 llvm::SetUnnamedAddr(f, false);
1513 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1518 if name == "simd_scatter" {
1519 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1520 // mask: <N x i{M}>) -> ()
1521 // * N: number of elements in the input vectors
1522 // * T: type of the element to load
1523 // * M: any integer width is supported, will be truncated to i1
1525 // All types must be simd vector types
1526 require_simd!(in_ty, "first");
1527 require_simd!(arg_tys[1], "second");
1528 require_simd!(arg_tys[2], "third");
1530 // Of the same length:
1531 require!(in_len == arg_tys[1].simd_size(tcx),
1532 "expected {} argument with length {} (same as input type `{}`), \
1533 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1534 arg_tys[1].simd_size(tcx));
1535 require!(in_len == arg_tys[2].simd_size(tcx),
1536 "expected {} argument with length {} (same as input type `{}`), \
1537 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1538 arg_tys[2].simd_size(tcx));
1540 // This counts how many pointers
1541 fn ptr_count(t: Ty<'_>) -> usize {
1543 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1549 fn non_ptr(t: Ty<'_>) -> Ty<'_> {
1551 ty::RawPtr(p) => non_ptr(p.ty),
1556 // The second argument must be a simd vector with an element type that's a pointer
1557 // to the element type of the first argument
1558 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1559 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1560 => (ptr_count(arg_tys[1].simd_type(tcx)),
1561 non_ptr(arg_tys[1].simd_type(tcx))),
1563 require!(false, "expected element type `{}` of second argument `{}` \
1564 to be a pointer to the element type `{}` of the first \
1565 argument `{}`, found `{}` != `*mut {}`",
1566 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1567 arg_tys[1].simd_type(tcx), in_elem);
1571 assert!(pointer_count > 0);
1572 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1573 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1575 // The element type of the third argument must be a signed integer type of any width:
1576 match arg_tys[2].simd_type(tcx).sty {
1579 require!(false, "expected element type `{}` of third argument `{}` \
1580 to be a signed integer type",
1581 arg_tys[2].simd_type(tcx), arg_tys[2]);
1585 // Alignment of T, must be a constant integer value:
1586 let alignment_ty = bx.type_i32();
1587 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1589 // Truncate the mask vector to a vector of i1s:
1590 let (mask, mask_ty) = {
1591 let i1 = bx.type_i1();
1592 let i1xn = bx.type_vector(i1, in_len as u64);
1593 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1596 let ret_t = bx.type_void();
1598 // Type of the vector of pointers:
1599 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1600 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1602 // Type of the vector of elements:
1603 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1604 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1606 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1607 llvm_elem_vec_str, llvm_pointer_vec_str);
1608 let f = bx.declare_cfn(&llvm_intrinsic,
1609 bx.type_func(&[llvm_elem_vec_ty,
1610 llvm_pointer_vec_ty,
1613 llvm::SetUnnamedAddr(f, false);
1614 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1619 macro_rules! arith_red {
1620 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1622 require!(ret_ty == in_elem,
1623 "expected return type `{}` (element of input `{}`), found `{}`",
1624 in_elem, in_ty, ret_ty);
1625 return match in_elem.sty {
1626 ty::Int(_) | ty::Uint(_) => {
1627 let r = bx.$integer_reduce(args[0].immediate());
1629 // if overflow occurs, the result is the
1630 // mathematical result modulo 2^n:
1631 if name.contains("mul") {
1632 Ok(bx.mul(args[1].immediate(), r))
1634 Ok(bx.add(args[1].immediate(), r))
1637 Ok(bx.$integer_reduce(args[0].immediate()))
1641 let acc = if $ordered {
1642 // ordered arithmetic reductions take an accumulator
1645 // unordered arithmetic reductions use the identity accumulator
1646 let identity_acc = if $name.contains("mul") { 1.0 } else { 0.0 };
1647 match f.bit_width() {
1648 32 => bx.const_real(bx.type_f32(), identity_acc),
1649 64 => bx.const_real(bx.type_f64(), identity_acc),
1652 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1653 $name, in_ty, in_elem, v, ret_ty
1658 Ok(bx.$float_reduce(acc, args[0].immediate()))
1662 "unsupported {} from `{}` with element `{}` to `{}`",
1663 $name, in_ty, in_elem, ret_ty
1671 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd, true);
1672 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul, true);
1673 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1674 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1676 macro_rules! minmax_red {
1677 ($name:tt: $int_red:ident, $float_red:ident) => {
1679 require!(ret_ty == in_elem,
1680 "expected return type `{}` (element of input `{}`), found `{}`",
1681 in_elem, in_ty, ret_ty);
1682 return match in_elem.sty {
1684 Ok(bx.$int_red(args[0].immediate(), true))
1687 Ok(bx.$int_red(args[0].immediate(), false))
1690 Ok(bx.$float_red(args[0].immediate()))
1693 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1694 $name, in_ty, in_elem, ret_ty)
1702 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1703 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1705 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1706 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1708 macro_rules! bitwise_red {
1709 ($name:tt : $red:ident, $boolean:expr) => {
1711 let input = if !$boolean {
1712 require!(ret_ty == in_elem,
1713 "expected return type `{}` (element of input `{}`), found `{}`",
1714 in_elem, in_ty, ret_ty);
1718 ty::Int(_) | ty::Uint(_) => {},
1720 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1721 $name, in_ty, in_elem, ret_ty)
1725 // boolean reductions operate on vectors of i1s:
1726 let i1 = bx.type_i1();
1727 let i1xn = bx.type_vector(i1, in_len as u64);
1728 bx.trunc(args[0].immediate(), i1xn)
1730 return match in_elem.sty {
1731 ty::Int(_) | ty::Uint(_) => {
1732 let r = bx.$red(input);
1737 bx.zext(r, bx.type_bool())
1742 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1743 $name, in_ty, in_elem, ret_ty)
1750 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1751 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1752 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1753 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1754 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1756 if name == "simd_cast" {
1757 require_simd!(ret_ty, "return");
1758 let out_len = ret_ty.simd_size(tcx);
1759 require!(in_len == out_len,
1760 "expected return type with length {} (same as input type `{}`), \
1761 found `{}` with length {}",
1764 // casting cares about nominal type, not just structural type
1765 let out_elem = ret_ty.simd_type(tcx);
1767 if in_elem == out_elem { return Ok(args[0].immediate()); }
1769 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1771 let (in_style, in_width) = match in_elem.sty {
1772 // vectors of pointer-sized integers should've been
1773 // disallowed before here, so this unwrap is safe.
1774 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1775 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1776 ty::Float(f) => (Style::Float, f.bit_width()),
1777 _ => (Style::Unsupported, 0)
1779 let (out_style, out_width) = match out_elem.sty {
1780 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1781 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1782 ty::Float(f) => (Style::Float, f.bit_width()),
1783 _ => (Style::Unsupported, 0)
1786 match (in_style, out_style) {
1787 (Style::Int(in_is_signed), Style::Int(_)) => {
1788 return Ok(match in_width.cmp(&out_width) {
1789 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1790 Ordering::Equal => args[0].immediate(),
1791 Ordering::Less => if in_is_signed {
1792 bx.sext(args[0].immediate(), llret_ty)
1794 bx.zext(args[0].immediate(), llret_ty)
1798 (Style::Int(in_is_signed), Style::Float) => {
1799 return Ok(if in_is_signed {
1800 bx.sitofp(args[0].immediate(), llret_ty)
1802 bx.uitofp(args[0].immediate(), llret_ty)
1805 (Style::Float, Style::Int(out_is_signed)) => {
1806 return Ok(if out_is_signed {
1807 bx.fptosi(args[0].immediate(), llret_ty)
1809 bx.fptoui(args[0].immediate(), llret_ty)
1812 (Style::Float, Style::Float) => {
1813 return Ok(match in_width.cmp(&out_width) {
1814 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1815 Ordering::Equal => args[0].immediate(),
1816 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1819 _ => {/* Unsupported. Fallthrough. */}
1822 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1826 macro_rules! arith {
1827 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1828 $(if name == stringify!($name) {
1830 $($(ty::$p(_))|* => {
1831 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1836 "unsupported operation on `{}` with element `{}`",
1843 simd_add: Uint, Int => add, Float => fadd;
1844 simd_sub: Uint, Int => sub, Float => fsub;
1845 simd_mul: Uint, Int => mul, Float => fmul;
1846 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1847 simd_rem: Uint => urem, Int => srem, Float => frem;
1848 simd_shl: Uint, Int => shl;
1849 simd_shr: Uint => lshr, Int => ashr;
1850 simd_and: Uint, Int => and;
1851 simd_or: Uint, Int => or;
1852 simd_xor: Uint, Int => xor;
1853 simd_fmax: Float => maxnum;
1854 simd_fmin: Float => minnum;
1858 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
1859 let lhs = args[0].immediate();
1860 let rhs = args[1].immediate();
1861 let is_add = name == "simd_saturating_add";
1862 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1863 let (signed, elem_width, elem_ty) = match in_elem.sty {
1867 i.bit_width().unwrap_or(ptr_bits),
1868 bx.cx.type_int_from_ty(i)
1873 i.bit_width().unwrap_or(ptr_bits),
1874 bx.cx.type_uint_from_ty(i)
1878 "expected element type `{}` of vector type `{}` \
1879 to be a signed or unsigned integer type",
1880 arg_tys[0].simd_type(tcx), arg_tys[0]
1884 let llvm_intrinsic = &format!(
1885 "llvm.{}{}.sat.v{}i{}",
1886 if signed { 's' } else { 'u' },
1887 if is_add { "add" } else { "sub" },
1890 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1892 let f = bx.declare_cfn(
1894 bx.type_func(&[vec_ty, vec_ty], vec_ty)
1896 llvm::SetUnnamedAddr(f, false);
1897 let v = bx.call(f, &[lhs, rhs], None);
1901 span_bug!(span, "unknown SIMD intrinsic");
1904 // Returns the width of an int Ty, and if it's signed or not
1905 // Returns None if the type is not an integer
1906 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1908 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1910 ty::Int(t) => Some((match t {
1911 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1912 ast::IntTy::I8 => 8,
1913 ast::IntTy::I16 => 16,
1914 ast::IntTy::I32 => 32,
1915 ast::IntTy::I64 => 64,
1916 ast::IntTy::I128 => 128,
1918 ty::Uint(t) => Some((match t {
1919 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1920 ast::UintTy::U8 => 8,
1921 ast::UintTy::U16 => 16,
1922 ast::UintTy::U32 => 32,
1923 ast::UintTy::U64 => 64,
1924 ast::UintTy::U128 => 128,
1930 // Returns the width of a float Ty
1931 // Returns None if the type is not a float
1932 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
1934 ty::Float(t) => Some(t.bit_width() as u64),