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 = rustc_mir::interpret::type_name(self.tcx, 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" | "exact_div" |
338 "rotate_left" | "rotate_right" | "saturating_add" | "saturating_sub" => {
340 match int_type_width_signed(ty, self) {
341 Some((width, signed)) =>
344 let y = self.const_bool(false);
345 let llfn = self.get_intrinsic(
346 &format!("llvm.{}.i{}", name, width),
348 self.call(llfn, &[args[0].immediate(), y], None)
350 "ctlz_nonzero" | "cttz_nonzero" => {
351 let y = self.const_bool(true);
352 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
353 let llfn = self.get_intrinsic(llvm_name);
354 self.call(llfn, &[args[0].immediate(), y], None)
356 "ctpop" => self.call(
357 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
358 &[args[0].immediate()],
363 args[0].immediate() // byte swap a u8/i8 is just a no-op
367 &format!("llvm.bswap.i{}", width),
369 &[args[0].immediate()],
377 &format!("llvm.bitreverse.i{}", width),
379 &[args[0].immediate()],
383 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
384 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
385 if signed { 's' } else { 'u' },
387 let llfn = self.get_intrinsic(&intrinsic);
389 // Convert `i1` to a `bool`, and write it to the out parameter
390 let pair = self.call(llfn, &[
394 let val = self.extract_value(pair, 0);
395 let overflow = self.extract_value(pair, 1);
396 let overflow = self.zext(overflow, self.type_bool());
398 let dest = result.project_field(self, 0);
399 self.store(val, dest.llval, dest.align);
400 let dest = result.project_field(self, 1);
401 self.store(overflow, dest.llval, dest.align);
405 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
406 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
407 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
410 self.exactsdiv(args[0].immediate(), args[1].immediate())
412 self.exactudiv(args[0].immediate(), args[1].immediate())
416 self.sdiv(args[0].immediate(), args[1].immediate())
418 self.udiv(args[0].immediate(), args[1].immediate())
422 self.srem(args[0].immediate(), args[1].immediate())
424 self.urem(args[0].immediate(), args[1].immediate())
426 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
429 self.ashr(args[0].immediate(), args[1].immediate())
431 self.lshr(args[0].immediate(), args[1].immediate())
433 "rotate_left" | "rotate_right" => {
434 let is_left = name == "rotate_left";
435 let val = args[0].immediate();
436 let raw_shift = args[1].immediate();
437 if llvm_util::get_major_version() >= 7 {
438 // rotate = funnel shift with first two args the same
439 let llvm_name = &format!("llvm.fsh{}.i{}",
440 if is_left { 'l' } else { 'r' }, width);
441 let llfn = self.get_intrinsic(llvm_name);
442 self.call(llfn, &[val, val, raw_shift], None)
444 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
445 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
446 let width = self.const_uint(
450 let shift = self.urem(raw_shift, width);
451 let width_minus_raw_shift = self.sub(width, raw_shift);
452 let inv_shift = self.urem(width_minus_raw_shift, width);
453 let shift1 = self.shl(
455 if is_left { shift } else { inv_shift },
457 let shift2 = self.lshr(
459 if !is_left { shift } else { inv_shift },
461 self.or(shift1, shift2)
464 "saturating_add" | "saturating_sub" => {
465 let is_add = name == "saturating_add";
466 let lhs = args[0].immediate();
467 let rhs = args[1].immediate();
468 if llvm_util::get_major_version() >= 8 {
469 let llvm_name = &format!("llvm.{}{}.sat.i{}",
470 if signed { 's' } else { 'u' },
471 if is_add { "add" } else { "sub" },
473 let llfn = self.get_intrinsic(llvm_name);
474 self.call(llfn, &[lhs, rhs], None)
476 let llvm_name = &format!("llvm.{}{}.with.overflow.i{}",
477 if signed { 's' } else { 'u' },
478 if is_add { "add" } else { "sub" },
480 let llfn = self.get_intrinsic(llvm_name);
481 let pair = self.call(llfn, &[lhs, rhs], None);
482 let val = self.extract_value(pair, 0);
483 let overflow = self.extract_value(pair, 1);
484 let llty = self.type_ix(width);
486 let limit = if signed {
487 let limit_lo = self.const_uint_big(
488 llty, (i128::MIN >> (128 - width)) as u128);
489 let limit_hi = self.const_uint_big(
490 llty, (i128::MAX >> (128 - width)) as u128);
492 IntPredicate::IntSLT, val, self.const_uint(llty, 0));
493 self.select(neg, limit_hi, limit_lo)
495 self.const_uint_big(llty, u128::MAX >> (128 - width))
497 self.const_uint(llty, 0)
499 self.select(overflow, limit, val)
505 span_invalid_monomorphization_error(
507 &format!("invalid monomorphization of `{}` intrinsic: \
508 expected basic integer type, found `{}`", name, ty));
514 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
515 match float_type_width(arg_tys[0]) {
518 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
519 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
520 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
521 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
522 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
526 span_invalid_monomorphization_error(
528 &format!("invalid monomorphization of `{}` intrinsic: \
529 expected basic float type, found `{}`", name, arg_tys[0]));
536 "discriminant_value" => {
537 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
540 name if name.starts_with("simd_") => {
541 match generic_simd_intrinsic(self, name,
550 // This requires that atomic intrinsics follow a specific naming pattern:
551 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
552 name if name.starts_with("atomic_") => {
553 use rustc_codegen_ssa::common::AtomicOrdering::*;
554 use rustc_codegen_ssa::common::
555 {SynchronizationScope, AtomicRmwBinOp};
557 let split: Vec<&str> = name.split('_').collect();
559 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
560 let (order, failorder) = match split.len() {
561 2 => (SequentiallyConsistent, SequentiallyConsistent),
562 3 => match split[2] {
563 "unordered" => (Unordered, Unordered),
564 "relaxed" => (Monotonic, Monotonic),
565 "acq" => (Acquire, Acquire),
566 "rel" => (Release, Monotonic),
567 "acqrel" => (AcquireRelease, Acquire),
568 "failrelaxed" if is_cxchg =>
569 (SequentiallyConsistent, Monotonic),
570 "failacq" if is_cxchg =>
571 (SequentiallyConsistent, Acquire),
572 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
574 4 => match (split[2], split[3]) {
575 ("acq", "failrelaxed") if is_cxchg =>
576 (Acquire, Monotonic),
577 ("acqrel", "failrelaxed") if is_cxchg =>
578 (AcquireRelease, Monotonic),
579 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
581 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
584 let invalid_monomorphization = |ty| {
585 span_invalid_monomorphization_error(tcx.sess, span,
586 &format!("invalid monomorphization of `{}` intrinsic: \
587 expected basic integer type, found `{}`", name, ty));
591 "cxchg" | "cxchgweak" => {
592 let ty = substs.type_at(0);
593 if int_type_width_signed(ty, self).is_some() {
594 let weak = split[1] == "cxchgweak";
595 let pair = self.atomic_cmpxchg(
602 let val = self.extract_value(pair, 0);
603 let success = self.extract_value(pair, 1);
604 let success = self.zext(success, self.type_bool());
606 let dest = result.project_field(self, 0);
607 self.store(val, dest.llval, dest.align);
608 let dest = result.project_field(self, 1);
609 self.store(success, dest.llval, dest.align);
612 return invalid_monomorphization(ty);
617 let ty = substs.type_at(0);
618 if int_type_width_signed(ty, self).is_some() {
619 let size = self.size_of(ty);
620 self.atomic_load(args[0].immediate(), order, size)
622 return invalid_monomorphization(ty);
627 let ty = substs.type_at(0);
628 if int_type_width_signed(ty, self).is_some() {
629 let size = self.size_of(ty);
638 return invalid_monomorphization(ty);
643 self.atomic_fence(order, SynchronizationScope::CrossThread);
647 "singlethreadfence" => {
648 self.atomic_fence(order, SynchronizationScope::SingleThread);
652 // These are all AtomicRMW ops
654 let atom_op = match op {
655 "xchg" => AtomicRmwBinOp::AtomicXchg,
656 "xadd" => AtomicRmwBinOp::AtomicAdd,
657 "xsub" => AtomicRmwBinOp::AtomicSub,
658 "and" => AtomicRmwBinOp::AtomicAnd,
659 "nand" => AtomicRmwBinOp::AtomicNand,
660 "or" => AtomicRmwBinOp::AtomicOr,
661 "xor" => AtomicRmwBinOp::AtomicXor,
662 "max" => AtomicRmwBinOp::AtomicMax,
663 "min" => AtomicRmwBinOp::AtomicMin,
664 "umax" => AtomicRmwBinOp::AtomicUMax,
665 "umin" => AtomicRmwBinOp::AtomicUMin,
666 _ => self.sess().fatal("unknown atomic operation")
669 let ty = substs.type_at(0);
670 if int_type_width_signed(ty, self).is_some() {
678 return invalid_monomorphization(ty);
684 "nontemporal_store" => {
685 let dst = args[0].deref(self.cx());
686 args[1].val.nontemporal_store(self, dst);
690 _ => bug!("unknown intrinsic '{}'", name),
693 if !fn_ty.ret.is_ignore() {
694 if let PassMode::Cast(ty) = fn_ty.ret.mode {
695 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
696 let ptr = self.pointercast(result.llval, ptr_llty);
697 self.store(llval, ptr, result.align);
699 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
700 .val.store(self, result);
705 fn abort(&mut self) {
706 let fnname = self.get_intrinsic(&("llvm.trap"));
707 self.call(fnname, &[], None);
710 fn assume(&mut self, val: Self::Value) {
711 let assume_intrinsic = self.get_intrinsic("llvm.assume");
712 self.call(assume_intrinsic, &[val], None);
715 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
716 let expect = self.get_intrinsic(&"llvm.expect.i1");
717 self.call(expect, &[cond, self.const_bool(expected)], None)
720 fn va_start(&mut self, list: &'ll Value) -> &'ll Value {
721 let target = &self.cx.tcx.sess.target.target;
722 let arch = &target.arch;
723 // A pointer to the architecture specific structure is passed to this
724 // function. For pointer variants (i686, RISC-V, Windows, etc), we
725 // should do do nothing, as the address to the pointer is needed. For
726 // architectures with a architecture specific structure (`Aarch64`,
727 // `X86_64`, etc), this function should load the structure from the
729 let va_list = match &**arch {
730 _ if target.options.is_like_windows => list,
731 "aarch64" if target.target_os == "ios" => list,
732 "aarch64" | "x86_64" | "powerpc" =>
733 self.load(list, self.tcx().data_layout.pointer_align.abi),
736 let intrinsic = self.cx().get_intrinsic("llvm.va_start");
737 self.call(intrinsic, &[va_list], None)
740 fn va_end(&mut self, list: &'ll Value) -> &'ll Value {
741 let target = &self.cx.tcx.sess.target.target;
742 let arch = &target.arch;
743 // See the comment in `va_start` for the purpose of the following.
744 let va_list = match &**arch {
745 _ if target.options.is_like_windows => list,
746 "aarch64" if target.target_os == "ios" => list,
747 "aarch64" | "x86_64" | "powerpc" =>
748 self.load(list, self.tcx().data_layout.pointer_align.abi),
751 let intrinsic = self.cx().get_intrinsic("llvm.va_end");
752 self.call(intrinsic, &[va_list], None)
757 bx: &mut Builder<'a, 'll, 'tcx>,
765 let (size, align) = bx.size_and_align_of(ty);
766 let size = bx.mul(bx.const_usize(size.bytes()), count);
767 let flags = if volatile {
773 bx.memmove(dst, align, src, align, size, flags);
775 bx.memcpy(dst, align, src, align, size, flags);
780 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 {
794 bx.memset(dst, val, size, align, flags);
798 bx: &mut Builder<'a, 'll, 'tcx>,
801 local_ptr: &'ll Value,
804 if bx.sess().no_landing_pads() {
805 bx.call(func, &[data], None);
806 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
807 bx.store(bx.const_null(bx.type_i8p()), dest, ptr_align);
808 } else if wants_msvc_seh(bx.sess()) {
809 codegen_msvc_try(bx, func, data, local_ptr, dest);
811 codegen_gnu_try(bx, func, data, local_ptr, dest);
815 // MSVC's definition of the `rust_try` function.
817 // This implementation uses the new exception handling instructions in LLVM
818 // which have support in LLVM for SEH on MSVC targets. Although these
819 // instructions are meant to work for all targets, as of the time of this
820 // writing, however, LLVM does not recommend the usage of these new instructions
821 // as the old ones are still more optimized.
823 bx: &mut Builder<'a, 'll, 'tcx>,
826 local_ptr: &'ll Value,
829 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
830 bx.set_personality_fn(bx.eh_personality());
832 let mut normal = bx.build_sibling_block("normal");
833 let mut catchswitch = bx.build_sibling_block("catchswitch");
834 let mut catchpad = bx.build_sibling_block("catchpad");
835 let mut caught = bx.build_sibling_block("caught");
837 let func = llvm::get_param(bx.llfn(), 0);
838 let data = llvm::get_param(bx.llfn(), 1);
839 let local_ptr = llvm::get_param(bx.llfn(), 2);
841 // We're generating an IR snippet that looks like:
843 // declare i32 @rust_try(%func, %data, %ptr) {
844 // %slot = alloca i64*
845 // invoke %func(%data) to label %normal unwind label %catchswitch
851 // %cs = catchswitch within none [%catchpad] unwind to caller
854 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
855 // %ptr[0] = %slot[0]
856 // %ptr[1] = %slot[1]
857 // catchret from %tok to label %caught
863 // This structure follows the basic usage of throw/try/catch in LLVM.
864 // For example, compile this C++ snippet to see what LLVM generates:
866 // #include <stdint.h>
868 // int bar(void (*foo)(void), uint64_t *ret) {
872 // } catch(uint64_t a[2]) {
879 // More information can be found in libstd's seh.rs implementation.
880 let i64p = bx.type_ptr_to(bx.type_i64());
881 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
882 let slot = bx.alloca(i64p, "slot", ptr_align);
883 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
885 normal.ret(bx.const_i32(0));
887 let cs = catchswitch.catch_switch(None, None, 1);
888 catchswitch.add_handler(cs, catchpad.llbb());
890 let tydesc = match bx.tcx().lang_items().msvc_try_filter() {
891 Some(did) => bx.get_static(did),
892 None => bug!("msvc_try_filter not defined"),
894 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.const_i32(0), slot]);
895 let addr = catchpad.load(slot, ptr_align);
897 let i64_align = bx.tcx().data_layout.i64_align.abi;
898 let arg1 = catchpad.load(addr, i64_align);
899 let val1 = bx.const_i32(1);
900 let gep1 = catchpad.inbounds_gep(addr, &[val1]);
901 let arg2 = catchpad.load(gep1, i64_align);
902 let local_ptr = catchpad.bitcast(local_ptr, i64p);
903 let gep2 = catchpad.inbounds_gep(local_ptr, &[val1]);
904 catchpad.store(arg1, local_ptr, i64_align);
905 catchpad.store(arg2, gep2, i64_align);
906 catchpad.catch_ret(&funclet, caught.llbb());
908 caught.ret(bx.const_i32(1));
911 // Note that no invoke is used here because by definition this function
912 // can't panic (that's what it's catching).
913 let ret = bx.call(llfn, &[func, data, local_ptr], None);
914 let i32_align = bx.tcx().data_layout.i32_align.abi;
915 bx.store(ret, dest, i32_align);
918 // Definition of the standard "try" function for Rust using the GNU-like model
919 // of exceptions (e.g., the normal semantics of LLVM's landingpad and invoke
922 // This codegen is a little surprising because we always call a shim
923 // function instead of inlining the call to `invoke` manually here. This is done
924 // because in LLVM we're only allowed to have one personality per function
925 // definition. The call to the `try` intrinsic is being inlined into the
926 // function calling it, and that function may already have other personality
927 // functions in play. By calling a shim we're guaranteed that our shim will have
928 // the right personality function.
930 bx: &mut Builder<'a, 'll, 'tcx>,
933 local_ptr: &'ll Value,
936 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
937 // Codegens the shims described above:
940 // invoke %func(%args...) normal %normal unwind %catch
946 // (ptr, _) = landingpad
947 // store ptr, %local_ptr
950 // Note that the `local_ptr` data passed into the `try` intrinsic is
951 // expected to be `*mut *mut u8` for this to actually work, but that's
952 // managed by the standard library.
954 let mut then = bx.build_sibling_block("then");
955 let mut catch = bx.build_sibling_block("catch");
957 let func = llvm::get_param(bx.llfn(), 0);
958 let data = llvm::get_param(bx.llfn(), 1);
959 let local_ptr = llvm::get_param(bx.llfn(), 2);
960 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
961 then.ret(bx.const_i32(0));
963 // Type indicator for the exception being thrown.
965 // The first value in this tuple is a pointer to the exception object
966 // being thrown. The second value is a "selector" indicating which of
967 // the landing pad clauses the exception's type had been matched to.
968 // rust_try ignores the selector.
969 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
970 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
971 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
972 let ptr = catch.extract_value(vals, 0);
973 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
974 let bitcast = catch.bitcast(local_ptr, bx.type_ptr_to(bx.type_i8p()));
975 catch.store(ptr, bitcast, ptr_align);
976 catch.ret(bx.const_i32(1));
979 // Note that no invoke is used here because by definition this function
980 // can't panic (that's what it's catching).
981 let ret = bx.call(llfn, &[func, data, local_ptr], None);
982 let i32_align = bx.tcx().data_layout.i32_align.abi;
983 bx.store(ret, dest, i32_align);
986 // Helper function to give a Block to a closure to codegen a shim function.
987 // This is currently primarily used for the `try` intrinsic functions above.
988 fn gen_fn<'ll, 'tcx>(
989 cx: &CodegenCx<'ll, 'tcx>,
991 inputs: Vec<Ty<'tcx>>,
993 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
995 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
999 hir::Unsafety::Unsafe,
1002 let llfn = cx.define_internal_fn(name, rust_fn_sig);
1003 attributes::from_fn_attrs(cx, llfn, None, rust_fn_sig);
1004 let bx = Builder::new_block(cx, llfn, "entry-block");
1009 // Helper function used to get a handle to the `__rust_try` function used to
1010 // catch exceptions.
1012 // This function is only generated once and is then cached.
1013 fn get_rust_try_fn<'ll, 'tcx>(
1014 cx: &CodegenCx<'ll, 'tcx>,
1015 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1017 if let Some(llfn) = cx.rust_try_fn.get() {
1021 // Define the type up front for the signature of the rust_try function.
1023 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1024 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1028 hir::Unsafety::Unsafe,
1031 let output = tcx.types.i32;
1032 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1033 cx.rust_try_fn.set(Some(rust_try));
1037 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1038 span_err!(a, b, E0511, "{}", c);
1041 fn generic_simd_intrinsic(
1042 bx: &mut Builder<'a, 'll, 'tcx>,
1044 callee_ty: Ty<'tcx>,
1045 args: &[OperandRef<'tcx, &'ll Value>],
1047 llret_ty: &'ll Type,
1049 ) -> Result<&'ll Value, ()> {
1050 // macros for error handling:
1051 macro_rules! emit_error {
1055 ($msg: tt, $($fmt: tt)*) => {
1056 span_invalid_monomorphization_error(
1058 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1063 macro_rules! return_error {
1066 emit_error!($($fmt)*);
1072 macro_rules! require {
1073 ($cond: expr, $($fmt: tt)*) => {
1075 return_error!($($fmt)*);
1080 macro_rules! require_simd {
1081 ($ty: expr, $position: expr) => {
1082 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1087 let sig = tcx.normalize_erasing_late_bound_regions(
1088 ty::ParamEnv::reveal_all(),
1089 &callee_ty.fn_sig(tcx),
1091 let arg_tys = sig.inputs();
1093 if name == "simd_select_bitmask" {
1094 let in_ty = arg_tys[0];
1095 let m_len = match in_ty.sty {
1096 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1097 // of intentional as there's not currently a use case for that.
1098 ty::Int(i) => i.bit_width().unwrap(),
1099 ty::Uint(i) => i.bit_width().unwrap(),
1100 _ => return_error!("`{}` is not an integral type", in_ty),
1102 require_simd!(arg_tys[1], "argument");
1103 let v_len = arg_tys[1].simd_size(tcx);
1104 require!(m_len == v_len,
1105 "mismatched lengths: mask length `{}` != other vector length `{}`",
1108 let i1 = bx.type_i1();
1109 let i1xn = bx.type_vector(i1, m_len as u64);
1110 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1111 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1114 // every intrinsic below takes a SIMD vector as its first argument
1115 require_simd!(arg_tys[0], "input");
1116 let in_ty = arg_tys[0];
1117 let in_elem = arg_tys[0].simd_type(tcx);
1118 let in_len = arg_tys[0].simd_size(tcx);
1120 let comparison = match name {
1121 "simd_eq" => Some(hir::BinOpKind::Eq),
1122 "simd_ne" => Some(hir::BinOpKind::Ne),
1123 "simd_lt" => Some(hir::BinOpKind::Lt),
1124 "simd_le" => Some(hir::BinOpKind::Le),
1125 "simd_gt" => Some(hir::BinOpKind::Gt),
1126 "simd_ge" => Some(hir::BinOpKind::Ge),
1130 if let Some(cmp_op) = comparison {
1131 require_simd!(ret_ty, "return");
1133 let out_len = ret_ty.simd_size(tcx);
1134 require!(in_len == out_len,
1135 "expected return type with length {} (same as input type `{}`), \
1136 found `{}` with length {}",
1139 require!(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1140 "expected return type with integer elements, found `{}` with non-integer `{}`",
1142 ret_ty.simd_type(tcx));
1144 return Ok(compare_simd_types(bx,
1145 args[0].immediate(),
1146 args[1].immediate(),
1152 if name.starts_with("simd_shuffle") {
1153 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1154 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1156 require_simd!(ret_ty, "return");
1158 let out_len = ret_ty.simd_size(tcx);
1159 require!(out_len == n,
1160 "expected return type of length {}, found `{}` with length {}",
1161 n, ret_ty, out_len);
1162 require!(in_elem == ret_ty.simd_type(tcx),
1163 "expected return element type `{}` (element of input `{}`), \
1164 found `{}` with element type `{}`",
1166 ret_ty, ret_ty.simd_type(tcx));
1168 let total_len = in_len as u128 * 2;
1170 let vector = args[2].immediate();
1172 let indices: Option<Vec<_>> = (0..n)
1175 let val = bx.const_get_elt(vector, i as u64);
1176 match bx.const_to_opt_u128(val, true) {
1178 emit_error!("shuffle index #{} is not a constant", arg_idx);
1181 Some(idx) if idx >= total_len => {
1182 emit_error!("shuffle index #{} is out of bounds (limit {})",
1183 arg_idx, total_len);
1186 Some(idx) => Some(bx.const_i32(idx as i32)),
1190 let indices = match indices {
1192 None => return Ok(bx.const_null(llret_ty))
1195 return Ok(bx.shuffle_vector(args[0].immediate(),
1196 args[1].immediate(),
1197 bx.const_vector(&indices)))
1200 if name == "simd_insert" {
1201 require!(in_elem == arg_tys[2],
1202 "expected inserted type `{}` (element of input `{}`), found `{}`",
1203 in_elem, in_ty, arg_tys[2]);
1204 return Ok(bx.insert_element(args[0].immediate(),
1205 args[2].immediate(),
1206 args[1].immediate()))
1208 if name == "simd_extract" {
1209 require!(ret_ty == in_elem,
1210 "expected return type `{}` (element of input `{}`), found `{}`",
1211 in_elem, in_ty, ret_ty);
1212 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1215 if name == "simd_select" {
1216 let m_elem_ty = in_elem;
1218 require_simd!(arg_tys[1], "argument");
1219 let v_len = arg_tys[1].simd_size(tcx);
1220 require!(m_len == v_len,
1221 "mismatched lengths: mask length `{}` != other vector length `{}`",
1224 match m_elem_ty.sty {
1226 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1228 // truncate the mask to a vector of i1s
1229 let i1 = bx.type_i1();
1230 let i1xn = bx.type_vector(i1, m_len as u64);
1231 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1232 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1235 if name == "simd_bitmask" {
1236 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1237 // vector mask and returns an unsigned integer containing the most
1238 // significant bit (MSB) of each lane.
1239 use rustc_target::abi::HasDataLayout;
1241 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1243 let expected_int_bits = in_len.max(8);
1245 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1247 "bitmask `{}`, expected `u{}`",
1248 ret_ty, expected_int_bits
1252 // Integer vector <i{in_bitwidth} x in_len>:
1253 let (i_xn, in_elem_bitwidth) = match in_elem.sty {
1255 args[0].immediate(),
1256 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1259 args[0].immediate(),
1260 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1263 "vector argument `{}`'s element type `{}`, expected integer element type",
1268 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1269 let shift_indices = vec![
1270 bx.cx.const_int(bx.type_ix(in_elem_bitwidth as _), (in_elem_bitwidth - 1) as _); in_len
1272 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1273 // Truncate vector to an <i1 x N>
1274 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len as _));
1275 // Bitcast <i1 x N> to iN:
1276 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len as _));
1277 // Zero-extend iN to the bitmask type:
1278 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits as _)));
1281 fn simd_simple_float_intrinsic(
1283 in_elem: &::rustc::ty::TyS<'_>,
1284 in_ty: &::rustc::ty::TyS<'_>,
1286 bx: &mut Builder<'a, 'll, 'tcx>,
1288 args: &[OperandRef<'tcx, &'ll Value>],
1289 ) -> Result<&'ll Value, ()> {
1290 macro_rules! emit_error {
1294 ($msg: tt, $($fmt: tt)*) => {
1295 span_invalid_monomorphization_error(
1297 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1301 macro_rules! return_error {
1304 emit_error!($($fmt)*);
1309 let ety = match in_elem.sty {
1310 ty::Float(f) if f.bit_width() == 32 => {
1311 if in_len < 2 || in_len > 16 {
1313 "unsupported floating-point vector `{}` with length `{}` \
1314 out-of-range [2, 16]",
1319 ty::Float(f) if f.bit_width() == 64 => {
1320 if in_len < 2 || in_len > 8 {
1321 return_error!("unsupported floating-point vector `{}` with length `{}` \
1322 out-of-range [2, 8]",
1328 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1332 return_error!("`{}` is not a floating-point type", in_ty);
1336 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1337 let intrinsic = bx.get_intrinsic(&llvm_name);
1338 let c = bx.call(intrinsic,
1339 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1341 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1347 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1350 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1353 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1356 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1359 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1362 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1365 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1368 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1371 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1374 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1377 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1380 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1383 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1386 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1388 _ => { /* fallthrough */ }
1392 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1393 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1394 fn llvm_vector_str(elem_ty: ty::Ty<'_>, vec_len: usize, no_pointers: usize) -> String {
1395 let p0s: String = "p0".repeat(no_pointers);
1397 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1398 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1399 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1400 _ => unreachable!(),
1404 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty<'_>, vec_len: usize,
1405 mut no_pointers: usize) -> &'ll Type {
1406 // FIXME: use cx.layout_of(ty).llvm_type() ?
1407 let mut elem_ty = match elem_ty.sty {
1408 ty::Int(v) => cx.type_int_from_ty( v),
1409 ty::Uint(v) => cx.type_uint_from_ty( v),
1410 ty::Float(v) => cx.type_float_from_ty( v),
1411 _ => unreachable!(),
1413 while no_pointers > 0 {
1414 elem_ty = cx.type_ptr_to(elem_ty);
1417 cx.type_vector(elem_ty, vec_len as u64)
1421 if name == "simd_gather" {
1422 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1423 // mask: <N x i{M}>) -> <N x T>
1424 // * N: number of elements in the input vectors
1425 // * T: type of the element to load
1426 // * M: any integer width is supported, will be truncated to i1
1428 // All types must be simd vector types
1429 require_simd!(in_ty, "first");
1430 require_simd!(arg_tys[1], "second");
1431 require_simd!(arg_tys[2], "third");
1432 require_simd!(ret_ty, "return");
1434 // Of the same length:
1435 require!(in_len == arg_tys[1].simd_size(tcx),
1436 "expected {} argument with length {} (same as input type `{}`), \
1437 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1438 arg_tys[1].simd_size(tcx));
1439 require!(in_len == arg_tys[2].simd_size(tcx),
1440 "expected {} argument with length {} (same as input type `{}`), \
1441 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1442 arg_tys[2].simd_size(tcx));
1444 // The return type must match the first argument type
1445 require!(ret_ty == in_ty,
1446 "expected return type `{}`, found `{}`",
1449 // This counts how many pointers
1450 fn ptr_count(t: ty::Ty<'_>) -> usize {
1452 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1458 fn non_ptr(t: ty::Ty<'_>) -> ty::Ty<'_> {
1460 ty::RawPtr(p) => non_ptr(p.ty),
1465 // The second argument must be a simd vector with an element type that's a pointer
1466 // to the element type of the first argument
1467 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1468 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1469 non_ptr(arg_tys[1].simd_type(tcx))),
1471 require!(false, "expected element type `{}` of second argument `{}` \
1472 to be a pointer to the element type `{}` of the first \
1473 argument `{}`, found `{}` != `*_ {}`",
1474 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1475 arg_tys[1].simd_type(tcx), in_elem);
1479 assert!(pointer_count > 0);
1480 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1481 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1483 // The element type of the third argument must be a signed integer type of any width:
1484 match arg_tys[2].simd_type(tcx).sty {
1487 require!(false, "expected element type `{}` of third argument `{}` \
1488 to be a signed integer type",
1489 arg_tys[2].simd_type(tcx), arg_tys[2]);
1493 // Alignment of T, must be a constant integer value:
1494 let alignment_ty = bx.type_i32();
1495 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1497 // Truncate the mask vector to a vector of i1s:
1498 let (mask, mask_ty) = {
1499 let i1 = bx.type_i1();
1500 let i1xn = bx.type_vector(i1, in_len as u64);
1501 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1504 // Type of the vector of pointers:
1505 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1506 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1508 // Type of the vector of elements:
1509 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1510 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1512 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1513 llvm_elem_vec_str, llvm_pointer_vec_str);
1514 let f = bx.declare_cfn(&llvm_intrinsic,
1516 llvm_pointer_vec_ty,
1519 llvm_elem_vec_ty], llvm_elem_vec_ty));
1520 llvm::SetUnnamedAddr(f, false);
1521 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1526 if name == "simd_scatter" {
1527 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1528 // mask: <N x i{M}>) -> ()
1529 // * N: number of elements in the input vectors
1530 // * T: type of the element to load
1531 // * M: any integer width is supported, will be truncated to i1
1533 // All types must be simd vector types
1534 require_simd!(in_ty, "first");
1535 require_simd!(arg_tys[1], "second");
1536 require_simd!(arg_tys[2], "third");
1538 // Of the same length:
1539 require!(in_len == arg_tys[1].simd_size(tcx),
1540 "expected {} argument with length {} (same as input type `{}`), \
1541 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1542 arg_tys[1].simd_size(tcx));
1543 require!(in_len == arg_tys[2].simd_size(tcx),
1544 "expected {} argument with length {} (same as input type `{}`), \
1545 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1546 arg_tys[2].simd_size(tcx));
1548 // This counts how many pointers
1549 fn ptr_count(t: ty::Ty<'_>) -> usize {
1551 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1557 fn non_ptr(t: ty::Ty<'_>) -> ty::Ty<'_> {
1559 ty::RawPtr(p) => non_ptr(p.ty),
1564 // The second argument must be a simd vector with an element type that's a pointer
1565 // to the element type of the first argument
1566 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1567 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1568 => (ptr_count(arg_tys[1].simd_type(tcx)),
1569 non_ptr(arg_tys[1].simd_type(tcx))),
1571 require!(false, "expected element type `{}` of second argument `{}` \
1572 to be a pointer to the element type `{}` of the first \
1573 argument `{}`, found `{}` != `*mut {}`",
1574 arg_tys[1].simd_type(tcx), arg_tys[1], in_elem, in_ty,
1575 arg_tys[1].simd_type(tcx), in_elem);
1579 assert!(pointer_count > 0);
1580 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1581 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1583 // The element type of the third argument must be a signed integer type of any width:
1584 match arg_tys[2].simd_type(tcx).sty {
1587 require!(false, "expected element type `{}` of third argument `{}` \
1588 to be a signed integer type",
1589 arg_tys[2].simd_type(tcx), arg_tys[2]);
1593 // Alignment of T, must be a constant integer value:
1594 let alignment_ty = bx.type_i32();
1595 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1597 // Truncate the mask vector to a vector of i1s:
1598 let (mask, mask_ty) = {
1599 let i1 = bx.type_i1();
1600 let i1xn = bx.type_vector(i1, in_len as u64);
1601 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1604 let ret_t = bx.type_void();
1606 // Type of the vector of pointers:
1607 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1608 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1610 // Type of the vector of elements:
1611 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1612 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1614 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1615 llvm_elem_vec_str, llvm_pointer_vec_str);
1616 let f = bx.declare_cfn(&llvm_intrinsic,
1617 bx.type_func(&[llvm_elem_vec_ty,
1618 llvm_pointer_vec_ty,
1621 llvm::SetUnnamedAddr(f, false);
1622 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1627 macro_rules! arith_red {
1628 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1630 require!(ret_ty == in_elem,
1631 "expected return type `{}` (element of input `{}`), found `{}`",
1632 in_elem, in_ty, ret_ty);
1633 return match in_elem.sty {
1634 ty::Int(_) | ty::Uint(_) => {
1635 let r = bx.$integer_reduce(args[0].immediate());
1637 // if overflow occurs, the result is the
1638 // mathematical result modulo 2^n:
1639 if name.contains("mul") {
1640 Ok(bx.mul(args[1].immediate(), r))
1642 Ok(bx.add(args[1].immediate(), r))
1645 Ok(bx.$integer_reduce(args[0].immediate()))
1649 // ordered arithmetic reductions take an accumulator
1650 let acc = if $ordered {
1651 let acc = args[1].immediate();
1652 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1653 // * if the accumulator of the fadd isn't 0, incorrect
1654 // code is generated
1655 // * if the accumulator of the fmul isn't 1, incorrect
1656 // code is generated
1657 match bx.const_get_real(acc) {
1658 None => return_error!("accumulator of {} is not a constant", $name),
1659 Some((v, loses_info)) => {
1660 if $name.contains("mul") && v != 1.0_f64 {
1661 return_error!("accumulator of {} is not 1.0", $name);
1662 } else if $name.contains("add") && v != 0.0_f64 {
1663 return_error!("accumulator of {} is not 0.0", $name);
1664 } else if loses_info {
1665 return_error!("accumulator of {} loses information", $name);
1671 // unordered arithmetic reductions do not:
1672 match f.bit_width() {
1673 32 => bx.const_undef(bx.type_f32()),
1674 64 => bx.const_undef(bx.type_f64()),
1677 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1678 $name, in_ty, in_elem, v, ret_ty
1683 Ok(bx.$float_reduce(acc, args[0].immediate()))
1687 "unsupported {} from `{}` with element `{}` to `{}`",
1688 $name, in_ty, in_elem, ret_ty
1696 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1697 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1698 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1699 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1701 macro_rules! minmax_red {
1702 ($name:tt: $int_red:ident, $float_red:ident) => {
1704 require!(ret_ty == in_elem,
1705 "expected return type `{}` (element of input `{}`), found `{}`",
1706 in_elem, in_ty, ret_ty);
1707 return match in_elem.sty {
1709 Ok(bx.$int_red(args[0].immediate(), true))
1712 Ok(bx.$int_red(args[0].immediate(), false))
1715 Ok(bx.$float_red(args[0].immediate()))
1718 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1719 $name, in_ty, in_elem, ret_ty)
1727 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1728 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1730 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1731 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1733 macro_rules! bitwise_red {
1734 ($name:tt : $red:ident, $boolean:expr) => {
1736 let input = if !$boolean {
1737 require!(ret_ty == in_elem,
1738 "expected return type `{}` (element of input `{}`), found `{}`",
1739 in_elem, in_ty, ret_ty);
1743 ty::Int(_) | ty::Uint(_) => {},
1745 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1746 $name, in_ty, in_elem, ret_ty)
1750 // boolean reductions operate on vectors of i1s:
1751 let i1 = bx.type_i1();
1752 let i1xn = bx.type_vector(i1, in_len as u64);
1753 bx.trunc(args[0].immediate(), i1xn)
1755 return match in_elem.sty {
1756 ty::Int(_) | ty::Uint(_) => {
1757 let r = bx.$red(input);
1762 bx.zext(r, bx.type_bool())
1767 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1768 $name, in_ty, in_elem, ret_ty)
1775 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1776 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1777 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1778 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1779 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1781 if name == "simd_cast" {
1782 require_simd!(ret_ty, "return");
1783 let out_len = ret_ty.simd_size(tcx);
1784 require!(in_len == out_len,
1785 "expected return type with length {} (same as input type `{}`), \
1786 found `{}` with length {}",
1789 // casting cares about nominal type, not just structural type
1790 let out_elem = ret_ty.simd_type(tcx);
1792 if in_elem == out_elem { return Ok(args[0].immediate()); }
1794 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1796 let (in_style, in_width) = match in_elem.sty {
1797 // vectors of pointer-sized integers should've been
1798 // disallowed before here, so this unwrap is safe.
1799 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1800 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1801 ty::Float(f) => (Style::Float, f.bit_width()),
1802 _ => (Style::Unsupported, 0)
1804 let (out_style, out_width) = match out_elem.sty {
1805 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1806 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1807 ty::Float(f) => (Style::Float, f.bit_width()),
1808 _ => (Style::Unsupported, 0)
1811 match (in_style, out_style) {
1812 (Style::Int(in_is_signed), Style::Int(_)) => {
1813 return Ok(match in_width.cmp(&out_width) {
1814 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1815 Ordering::Equal => args[0].immediate(),
1816 Ordering::Less => if in_is_signed {
1817 bx.sext(args[0].immediate(), llret_ty)
1819 bx.zext(args[0].immediate(), llret_ty)
1823 (Style::Int(in_is_signed), Style::Float) => {
1824 return Ok(if in_is_signed {
1825 bx.sitofp(args[0].immediate(), llret_ty)
1827 bx.uitofp(args[0].immediate(), llret_ty)
1830 (Style::Float, Style::Int(out_is_signed)) => {
1831 return Ok(if out_is_signed {
1832 bx.fptosi(args[0].immediate(), llret_ty)
1834 bx.fptoui(args[0].immediate(), llret_ty)
1837 (Style::Float, Style::Float) => {
1838 return Ok(match in_width.cmp(&out_width) {
1839 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1840 Ordering::Equal => args[0].immediate(),
1841 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1844 _ => {/* Unsupported. Fallthrough. */}
1847 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1851 macro_rules! arith {
1852 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1853 $(if name == stringify!($name) {
1855 $($(ty::$p(_))|* => {
1856 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1861 "unsupported operation on `{}` with element `{}`",
1868 simd_add: Uint, Int => add, Float => fadd;
1869 simd_sub: Uint, Int => sub, Float => fsub;
1870 simd_mul: Uint, Int => mul, Float => fmul;
1871 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1872 simd_rem: Uint => urem, Int => srem, Float => frem;
1873 simd_shl: Uint, Int => shl;
1874 simd_shr: Uint => lshr, Int => ashr;
1875 simd_and: Uint, Int => and;
1876 simd_or: Uint, Int => or;
1877 simd_xor: Uint, Int => xor;
1878 simd_fmax: Float => maxnum;
1879 simd_fmin: Float => minnum;
1883 if name == "simd_saturating_add" || name == "simd_saturating_sub" {
1884 let lhs = args[0].immediate();
1885 let rhs = args[1].immediate();
1886 let is_add = name == "simd_saturating_add";
1887 let ptr_bits = bx.tcx().data_layout.pointer_size.bits() as _;
1888 let (signed, elem_width, elem_ty) = match in_elem.sty {
1892 i.bit_width().unwrap_or(ptr_bits),
1893 bx.cx.type_int_from_ty(i)
1898 i.bit_width().unwrap_or(ptr_bits),
1899 bx.cx.type_uint_from_ty(i)
1903 "expected element type `{}` of vector type `{}` \
1904 to be a signed or unsigned integer type",
1905 arg_tys[0].simd_type(tcx), arg_tys[0]
1909 let llvm_intrinsic = &format!(
1910 "llvm.{}{}.sat.v{}i{}",
1911 if signed { 's' } else { 'u' },
1912 if is_add { "add" } else { "sub" },
1915 let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64);
1917 let f = bx.declare_cfn(
1919 bx.type_func(&[vec_ty, vec_ty], vec_ty)
1921 llvm::SetUnnamedAddr(f, false);
1922 let v = bx.call(f, &[lhs, rhs], None);
1926 span_bug!(span, "unknown SIMD intrinsic");
1929 // Returns the width of an int Ty, and if it's signed or not
1930 // Returns None if the type is not an integer
1931 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1933 fn int_type_width_signed(ty: Ty<'_>, cx: &CodegenCx<'_, '_>) -> Option<(u64, bool)> {
1935 ty::Int(t) => Some((match t {
1936 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1937 ast::IntTy::I8 => 8,
1938 ast::IntTy::I16 => 16,
1939 ast::IntTy::I32 => 32,
1940 ast::IntTy::I64 => 64,
1941 ast::IntTy::I128 => 128,
1943 ty::Uint(t) => Some((match t {
1944 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1945 ast::UintTy::U8 => 8,
1946 ast::UintTy::U16 => 16,
1947 ast::UintTy::U32 => 32,
1948 ast::UintTy::U64 => 64,
1949 ast::UintTy::U128 => 128,
1955 // Returns the width of a float Ty
1956 // Returns None if the type is not a float
1957 fn float_type_width(ty: Ty<'_>) -> Option<u64> {
1959 ty::Float(t) => Some(t.bit_width() as u64),