1 #![allow(non_upper_case_globals)]
6 use abi::{Abi, FnType, LlvmType, PassMode};
7 use rustc_codegen_ssa::MemFlags;
8 use rustc_codegen_ssa::mir::place::PlaceRef;
9 use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
10 use rustc_codegen_ssa::glue;
11 use rustc_codegen_ssa::base::{to_immediate, wants_msvc_seh, compare_simd_types};
12 use context::CodegenCx;
14 use type_of::LayoutLlvmExt;
15 use rustc::ty::{self, Ty};
16 use rustc::ty::layout::{self, LayoutOf, HasTyCtxt, Primitive};
17 use rustc_codegen_ssa::common::{IntPredicate, TypeKind};
19 use syntax::ast::{self, FloatTy};
20 use syntax::symbol::Symbol;
23 use va_arg::emit_va_arg;
25 use rustc_codegen_ssa::traits::*;
27 use rustc::session::Session;
30 use std::cmp::Ordering;
31 use std::{iter, i128, u128};
33 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
34 let llvm_name = match name {
35 "sqrtf32" => "llvm.sqrt.f32",
36 "sqrtf64" => "llvm.sqrt.f64",
37 "powif32" => "llvm.powi.f32",
38 "powif64" => "llvm.powi.f64",
39 "sinf32" => "llvm.sin.f32",
40 "sinf64" => "llvm.sin.f64",
41 "cosf32" => "llvm.cos.f32",
42 "cosf64" => "llvm.cos.f64",
43 "powf32" => "llvm.pow.f32",
44 "powf64" => "llvm.pow.f64",
45 "expf32" => "llvm.exp.f32",
46 "expf64" => "llvm.exp.f64",
47 "exp2f32" => "llvm.exp2.f32",
48 "exp2f64" => "llvm.exp2.f64",
49 "logf32" => "llvm.log.f32",
50 "logf64" => "llvm.log.f64",
51 "log10f32" => "llvm.log10.f32",
52 "log10f64" => "llvm.log10.f64",
53 "log2f32" => "llvm.log2.f32",
54 "log2f64" => "llvm.log2.f64",
55 "fmaf32" => "llvm.fma.f32",
56 "fmaf64" => "llvm.fma.f64",
57 "fabsf32" => "llvm.fabs.f32",
58 "fabsf64" => "llvm.fabs.f64",
59 "copysignf32" => "llvm.copysign.f32",
60 "copysignf64" => "llvm.copysign.f64",
61 "floorf32" => "llvm.floor.f32",
62 "floorf64" => "llvm.floor.f64",
63 "ceilf32" => "llvm.ceil.f32",
64 "ceilf64" => "llvm.ceil.f64",
65 "truncf32" => "llvm.trunc.f32",
66 "truncf64" => "llvm.trunc.f64",
67 "rintf32" => "llvm.rint.f32",
68 "rintf64" => "llvm.rint.f64",
69 "nearbyintf32" => "llvm.nearbyint.f32",
70 "nearbyintf64" => "llvm.nearbyint.f64",
71 "roundf32" => "llvm.round.f32",
72 "roundf64" => "llvm.round.f64",
73 "assume" => "llvm.assume",
74 "abort" => "llvm.trap",
77 Some(cx.get_intrinsic(&llvm_name))
80 impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> {
81 fn codegen_intrinsic_call(
84 fn_ty: &FnType<'tcx, Ty<'tcx>>,
85 args: &[OperandRef<'tcx, &'ll Value>],
91 let (def_id, substs) = match callee_ty.sty {
92 ty::FnDef(def_id, substs) => (def_id, substs),
93 _ => bug!("expected fn item type, found {}", callee_ty)
96 let sig = callee_ty.fn_sig(tcx);
97 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
98 let arg_tys = sig.inputs();
99 let ret_ty = sig.output();
100 let name = &*tcx.item_name(def_id).as_str();
102 let llret_ty = self.layout_of(ret_ty).llvm_type(self);
103 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align.abi);
105 let simple = get_simple_intrinsic(self, name);
106 let llval = match name {
107 _ if simple.is_some() => {
108 self.call(simple.unwrap(),
109 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
116 let expect = self.get_intrinsic(&("llvm.expect.i1"));
117 self.call(expect, &[args[0].immediate(), self.const_bool(true)], None)
120 let expect = self.get_intrinsic(&("llvm.expect.i1"));
121 self.call(expect, &[args[0].immediate(), self.const_bool(false)], None)
132 let llfn = self.get_intrinsic(&("llvm.debugtrap"));
133 self.call(llfn, &[], None)
136 let tp_ty = substs.type_at(0);
137 self.const_usize(self.size_of(tp_ty).bytes())
139 func @ "va_start" | func @ "va_end" => {
140 let va_list = match (tcx.lang_items().va_list(), &result.layout.ty.sty) {
141 (Some(did), ty::Adt(def, _)) if def.did == did => args[0].immediate(),
142 (Some(_), _) => self.load(args[0].immediate(),
143 tcx.data_layout.pointer_align.abi),
144 (None, _) => bug!("va_list language item must be defined")
146 let intrinsic = self.cx().get_intrinsic(&format!("llvm.{}", func));
147 self.call(intrinsic, &[va_list], None)
150 let va_list = match (tcx.lang_items().va_list(), &result.layout.ty.sty) {
151 (Some(did), ty::Adt(def, _)) if def.did == did => args[0].immediate(),
152 (Some(_), _) => self.load(args[0].immediate(),
153 tcx.data_layout.pointer_align.abi),
154 (None, _) => bug!("va_list language item must be defined")
156 let intrinsic = self.cx().get_intrinsic(&("llvm.va_copy"));
157 self.call(intrinsic, &[llresult, va_list], None);
161 match fn_ty.ret.layout.abi {
162 layout::Abi::Scalar(ref scalar) => {
164 Primitive::Int(..) => {
165 if self.cx().size_of(ret_ty).bytes() < 4 {
166 // va_arg should not be called on a integer type
167 // less than 4 bytes in length. If it is, promote
168 // the integer to a `i32` and truncate the result
169 // back to the smaller type.
170 let promoted_result = emit_va_arg(self, args[0],
172 self.trunc(promoted_result, llret_ty)
174 emit_va_arg(self, args[0], ret_ty)
177 Primitive::Float(FloatTy::F64) |
178 Primitive::Pointer => {
179 emit_va_arg(self, args[0], ret_ty)
181 // `va_arg` should never be used with the return type f32.
182 Primitive::Float(FloatTy::F32) => {
183 bug!("the va_arg intrinsic does not work with `f32`")
188 bug!("the va_arg intrinsic does not work with non-scalar types")
193 let tp_ty = substs.type_at(0);
194 if let OperandValue::Pair(_, meta) = args[0].val {
196 glue::size_and_align_of_dst(self, tp_ty, Some(meta));
199 self.const_usize(self.size_of(tp_ty).bytes())
203 let tp_ty = substs.type_at(0);
204 self.const_usize(self.align_of(tp_ty).bytes())
206 "min_align_of_val" => {
207 let tp_ty = substs.type_at(0);
208 if let OperandValue::Pair(_, meta) = args[0].val {
210 glue::size_and_align_of_dst(self, tp_ty, Some(meta));
213 self.const_usize(self.align_of(tp_ty).bytes())
217 let tp_ty = substs.type_at(0);
218 self.const_usize(self.layout_of(tp_ty).align.pref.bytes())
221 let tp_ty = substs.type_at(0);
222 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
223 self.const_str_slice(ty_name)
226 self.const_u64(self.tcx.type_id_hash(substs.type_at(0)))
229 let ty = substs.type_at(0);
230 if !self.layout_of(ty).is_zst() {
231 // Just zero out the stack slot.
232 // If we store a zero constant, LLVM will drown in vreg allocation for large
233 // data structures, and the generated code will be awful. (A telltale sign of
234 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
246 // Effectively no-ops
247 "uninit" | "forget" => {
251 let tp_ty = substs.type_at(0);
253 self.const_bool(self.type_needs_drop(tp_ty))
256 let ptr = args[0].immediate();
257 let offset = args[1].immediate();
258 self.inbounds_gep(ptr, &[offset])
261 let ptr = args[0].immediate();
262 let offset = args[1].immediate();
263 self.gep(ptr, &[offset])
266 "copy_nonoverlapping" => {
267 copy_intrinsic(self, false, false, substs.type_at(0),
268 args[1].immediate(), args[0].immediate(), args[2].immediate());
272 copy_intrinsic(self, true, false, substs.type_at(0),
273 args[1].immediate(), args[0].immediate(), args[2].immediate());
277 memset_intrinsic(self, false, substs.type_at(0),
278 args[0].immediate(), args[1].immediate(), args[2].immediate());
282 "volatile_copy_nonoverlapping_memory" => {
283 copy_intrinsic(self, false, true, substs.type_at(0),
284 args[0].immediate(), args[1].immediate(), args[2].immediate());
287 "volatile_copy_memory" => {
288 copy_intrinsic(self, true, true, substs.type_at(0),
289 args[0].immediate(), args[1].immediate(), args[2].immediate());
292 "volatile_set_memory" => {
293 memset_intrinsic(self, true, substs.type_at(0),
294 args[0].immediate(), args[1].immediate(), args[2].immediate());
297 "volatile_load" | "unaligned_volatile_load" => {
298 let tp_ty = substs.type_at(0);
299 let mut ptr = args[0].immediate();
300 if let PassMode::Cast(ty) = fn_ty.ret.mode {
301 ptr = self.pointercast(ptr, self.type_ptr_to(ty.llvm_type(self)));
303 let load = self.volatile_load(ptr);
304 let align = if name == "unaligned_volatile_load" {
307 self.align_of(tp_ty).bytes() as u32
310 llvm::LLVMSetAlignment(load, align);
312 to_immediate(self, load, self.layout_of(tp_ty))
314 "volatile_store" => {
315 let dst = args[0].deref(self.cx());
316 args[1].val.volatile_store(self, dst);
319 "unaligned_volatile_store" => {
320 let dst = args[0].deref(self.cx());
321 args[1].val.unaligned_volatile_store(self, dst);
324 "prefetch_read_data" | "prefetch_write_data" |
325 "prefetch_read_instruction" | "prefetch_write_instruction" => {
326 let expect = self.get_intrinsic(&("llvm.prefetch"));
327 let (rw, cache_type) = match name {
328 "prefetch_read_data" => (0, 1),
329 "prefetch_write_data" => (1, 1),
330 "prefetch_read_instruction" => (0, 0),
331 "prefetch_write_instruction" => (1, 0),
338 self.const_i32(cache_type)
341 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
342 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
343 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
344 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
345 "rotate_left" | "rotate_right" | "saturating_add" | "saturating_sub" => {
347 match int_type_width_signed(ty, self) {
348 Some((width, signed)) =>
351 let y = self.const_bool(false);
352 let llfn = self.get_intrinsic(
353 &format!("llvm.{}.i{}", name, width),
355 self.call(llfn, &[args[0].immediate(), y], None)
357 "ctlz_nonzero" | "cttz_nonzero" => {
358 let y = self.const_bool(true);
359 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
360 let llfn = self.get_intrinsic(llvm_name);
361 self.call(llfn, &[args[0].immediate(), y], None)
363 "ctpop" => self.call(
364 self.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
365 &[args[0].immediate()],
370 args[0].immediate() // byte swap a u8/i8 is just a no-op
374 &format!("llvm.bswap.i{}", width),
376 &[args[0].immediate()],
384 &format!("llvm.bitreverse.i{}", width),
386 &[args[0].immediate()],
390 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
391 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
392 if signed { 's' } else { 'u' },
394 let llfn = self.get_intrinsic(&intrinsic);
396 // Convert `i1` to a `bool`, and write it to the out parameter
397 let pair = self.call(llfn, &[
401 let val = self.extract_value(pair, 0);
402 let overflow = self.extract_value(pair, 1);
403 let overflow = self.zext(overflow, self.type_bool());
405 let dest = result.project_field(self, 0);
406 self.store(val, dest.llval, dest.align);
407 let dest = result.project_field(self, 1);
408 self.store(overflow, dest.llval, dest.align);
412 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
413 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
414 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
417 self.exactsdiv(args[0].immediate(), args[1].immediate())
419 self.exactudiv(args[0].immediate(), args[1].immediate())
423 self.sdiv(args[0].immediate(), args[1].immediate())
425 self.udiv(args[0].immediate(), args[1].immediate())
429 self.srem(args[0].immediate(), args[1].immediate())
431 self.urem(args[0].immediate(), args[1].immediate())
433 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
436 self.ashr(args[0].immediate(), args[1].immediate())
438 self.lshr(args[0].immediate(), args[1].immediate())
440 "rotate_left" | "rotate_right" => {
441 let is_left = name == "rotate_left";
442 let val = args[0].immediate();
443 let raw_shift = args[1].immediate();
444 if llvm_util::get_major_version() >= 7 {
445 // rotate = funnel shift with first two args the same
446 let llvm_name = &format!("llvm.fsh{}.i{}",
447 if is_left { 'l' } else { 'r' }, width);
448 let llfn = self.get_intrinsic(llvm_name);
449 self.call(llfn, &[val, val, raw_shift], None)
451 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
452 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
453 let width = self.const_uint(
457 let shift = self.urem(raw_shift, width);
458 let width_minus_raw_shift = self.sub(width, raw_shift);
459 let inv_shift = self.urem(width_minus_raw_shift, width);
460 let shift1 = self.shl(
462 if is_left { shift } else { inv_shift },
464 let shift2 = self.lshr(
466 if !is_left { shift } else { inv_shift },
468 self.or(shift1, shift2)
471 "saturating_add" | "saturating_sub" => {
472 let is_add = name == "saturating_add";
473 let lhs = args[0].immediate();
474 let rhs = args[1].immediate();
475 if llvm_util::get_major_version() >= 8 {
476 let llvm_name = &format!("llvm.{}{}.sat.i{}",
477 if signed { 's' } else { 'u' },
478 if is_add { "add" } else { "sub" },
480 let llfn = self.get_intrinsic(llvm_name);
481 self.call(llfn, &[lhs, rhs], None)
483 let llvm_name = &format!("llvm.{}{}.with.overflow.i{}",
484 if signed { 's' } else { 'u' },
485 if is_add { "add" } else { "sub" },
487 let llfn = self.get_intrinsic(llvm_name);
488 let pair = self.call(llfn, &[lhs, rhs], None);
489 let val = self.extract_value(pair, 0);
490 let overflow = self.extract_value(pair, 1);
491 let llty = self.type_ix(width);
493 let limit = if signed {
494 let limit_lo = self.const_uint_big(
495 llty, (i128::MIN >> (128 - width)) as u128);
496 let limit_hi = self.const_uint_big(
497 llty, (i128::MAX >> (128 - width)) as u128);
499 IntPredicate::IntSLT, val, self.const_uint(llty, 0));
500 self.select(neg, limit_hi, limit_lo)
502 self.const_uint_big(llty, u128::MAX >> (128 - width))
504 self.const_uint(llty, 0)
506 self.select(overflow, limit, val)
512 span_invalid_monomorphization_error(
514 &format!("invalid monomorphization of `{}` intrinsic: \
515 expected basic integer type, found `{}`", name, ty));
521 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
522 let sty = &arg_tys[0].sty;
523 match float_type_width(sty) {
526 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
527 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
528 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
529 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
530 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
534 span_invalid_monomorphization_error(
536 &format!("invalid monomorphization of `{}` intrinsic: \
537 expected basic float type, found `{}`", name, sty));
544 "discriminant_value" => {
545 args[0].deref(self.cx()).codegen_get_discr(self, ret_ty)
548 name if name.starts_with("simd_") => {
549 match generic_simd_intrinsic(self, name,
558 // This requires that atomic intrinsics follow a specific naming pattern:
559 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
560 name if name.starts_with("atomic_") => {
561 use rustc_codegen_ssa::common::AtomicOrdering::*;
562 use rustc_codegen_ssa::common::
563 {SynchronizationScope, AtomicRmwBinOp};
565 let split: Vec<&str> = name.split('_').collect();
567 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
568 let (order, failorder) = match split.len() {
569 2 => (SequentiallyConsistent, SequentiallyConsistent),
570 3 => match split[2] {
571 "unordered" => (Unordered, Unordered),
572 "relaxed" => (Monotonic, Monotonic),
573 "acq" => (Acquire, Acquire),
574 "rel" => (Release, Monotonic),
575 "acqrel" => (AcquireRelease, Acquire),
576 "failrelaxed" if is_cxchg =>
577 (SequentiallyConsistent, Monotonic),
578 "failacq" if is_cxchg =>
579 (SequentiallyConsistent, Acquire),
580 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
582 4 => match (split[2], split[3]) {
583 ("acq", "failrelaxed") if is_cxchg =>
584 (Acquire, Monotonic),
585 ("acqrel", "failrelaxed") if is_cxchg =>
586 (AcquireRelease, Monotonic),
587 _ => self.sess().fatal("unknown ordering in atomic intrinsic")
589 _ => self.sess().fatal("Atomic intrinsic not in correct format"),
592 let invalid_monomorphization = |ty| {
593 span_invalid_monomorphization_error(tcx.sess, span,
594 &format!("invalid monomorphization of `{}` intrinsic: \
595 expected basic integer type, found `{}`", name, ty));
599 "cxchg" | "cxchgweak" => {
600 let ty = substs.type_at(0);
601 if int_type_width_signed(ty, self).is_some() {
602 let weak = split[1] == "cxchgweak";
603 let pair = self.atomic_cmpxchg(
610 let val = self.extract_value(pair, 0);
611 let success = self.extract_value(pair, 1);
612 let success = self.zext(success, self.type_bool());
614 let dest = result.project_field(self, 0);
615 self.store(val, dest.llval, dest.align);
616 let dest = result.project_field(self, 1);
617 self.store(success, dest.llval, dest.align);
620 return invalid_monomorphization(ty);
625 let ty = substs.type_at(0);
626 if int_type_width_signed(ty, self).is_some() {
627 let size = self.size_of(ty);
628 self.atomic_load(args[0].immediate(), order, size)
630 return invalid_monomorphization(ty);
635 let ty = substs.type_at(0);
636 if int_type_width_signed(ty, self).is_some() {
637 let size = self.size_of(ty);
646 return invalid_monomorphization(ty);
651 self.atomic_fence(order, SynchronizationScope::CrossThread);
655 "singlethreadfence" => {
656 self.atomic_fence(order, SynchronizationScope::SingleThread);
660 // These are all AtomicRMW ops
662 let atom_op = match op {
663 "xchg" => AtomicRmwBinOp::AtomicXchg,
664 "xadd" => AtomicRmwBinOp::AtomicAdd,
665 "xsub" => AtomicRmwBinOp::AtomicSub,
666 "and" => AtomicRmwBinOp::AtomicAnd,
667 "nand" => AtomicRmwBinOp::AtomicNand,
668 "or" => AtomicRmwBinOp::AtomicOr,
669 "xor" => AtomicRmwBinOp::AtomicXor,
670 "max" => AtomicRmwBinOp::AtomicMax,
671 "min" => AtomicRmwBinOp::AtomicMin,
672 "umax" => AtomicRmwBinOp::AtomicUMax,
673 "umin" => AtomicRmwBinOp::AtomicUMin,
674 _ => self.sess().fatal("unknown atomic operation")
677 let ty = substs.type_at(0);
678 if int_type_width_signed(ty, self).is_some() {
686 return invalid_monomorphization(ty);
692 "nontemporal_store" => {
693 let dst = args[0].deref(self.cx());
694 args[1].val.nontemporal_store(self, dst);
698 _ => bug!("unknown intrinsic '{}'", name),
701 if !fn_ty.ret.is_ignore() {
702 if let PassMode::Cast(ty) = fn_ty.ret.mode {
703 let ptr_llty = self.type_ptr_to(ty.llvm_type(self));
704 let ptr = self.pointercast(result.llval, ptr_llty);
705 self.store(llval, ptr, result.align);
707 OperandRef::from_immediate_or_packed_pair(self, llval, result.layout)
708 .val.store(self, result);
713 fn abort(&mut self) {
714 let fnname = self.get_intrinsic(&("llvm.trap"));
715 self.call(fnname, &[], None);
718 fn assume(&mut self, val: Self::Value) {
719 let assume_intrinsic = self.get_intrinsic("llvm.assume");
720 self.call(assume_intrinsic, &[val], None);
723 fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value {
724 let expect = self.get_intrinsic(&"llvm.expect.i1");
725 self.call(expect, &[cond, self.const_bool(expected)], None)
730 bx: &mut Builder<'a, 'll, 'tcx>,
738 let (size, align) = bx.size_and_align_of(ty);
739 let size = bx.mul(bx.const_usize(size.bytes()), count);
740 let flags = if volatile {
746 bx.memmove(dst, align, src, align, size, flags);
748 bx.memcpy(dst, align, src, align, size, flags);
753 bx: &mut Builder<'a, 'll, 'tcx>,
760 let (size, align) = bx.size_and_align_of(ty);
761 let size = bx.mul(bx.const_usize(size.bytes()), count);
762 let flags = if volatile {
767 bx.memset(dst, val, size, align, flags);
771 bx: &mut Builder<'a, 'll, 'tcx>,
774 local_ptr: &'ll Value,
777 if bx.sess().no_landing_pads() {
778 bx.call(func, &[data], None);
779 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
780 bx.store(bx.const_null(bx.type_i8p()), dest, ptr_align);
781 } else if wants_msvc_seh(bx.sess()) {
782 codegen_msvc_try(bx, func, data, local_ptr, dest);
784 codegen_gnu_try(bx, func, data, local_ptr, dest);
788 // MSVC's definition of the `rust_try` function.
790 // This implementation uses the new exception handling instructions in LLVM
791 // which have support in LLVM for SEH on MSVC targets. Although these
792 // instructions are meant to work for all targets, as of the time of this
793 // writing, however, LLVM does not recommend the usage of these new instructions
794 // as the old ones are still more optimized.
796 bx: &mut Builder<'a, 'll, 'tcx>,
799 local_ptr: &'ll Value,
802 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
803 bx.set_personality_fn(bx.eh_personality());
805 let mut normal = bx.build_sibling_block("normal");
806 let mut catchswitch = bx.build_sibling_block("catchswitch");
807 let mut catchpad = bx.build_sibling_block("catchpad");
808 let mut caught = bx.build_sibling_block("caught");
810 let func = llvm::get_param(bx.llfn(), 0);
811 let data = llvm::get_param(bx.llfn(), 1);
812 let local_ptr = llvm::get_param(bx.llfn(), 2);
814 // We're generating an IR snippet that looks like:
816 // declare i32 @rust_try(%func, %data, %ptr) {
817 // %slot = alloca i64*
818 // invoke %func(%data) to label %normal unwind label %catchswitch
824 // %cs = catchswitch within none [%catchpad] unwind to caller
827 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
828 // %ptr[0] = %slot[0]
829 // %ptr[1] = %slot[1]
830 // catchret from %tok to label %caught
836 // This structure follows the basic usage of throw/try/catch in LLVM.
837 // For example, compile this C++ snippet to see what LLVM generates:
839 // #include <stdint.h>
841 // int bar(void (*foo)(void), uint64_t *ret) {
845 // } catch(uint64_t a[2]) {
852 // More information can be found in libstd's seh.rs implementation.
853 let i64p = bx.type_ptr_to(bx.type_i64());
854 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
855 let slot = bx.alloca(i64p, "slot", ptr_align);
856 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
858 normal.ret(bx.const_i32(0));
860 let cs = catchswitch.catch_switch(None, None, 1);
861 catchswitch.add_handler(cs, catchpad.llbb());
863 let tydesc = match bx.tcx().lang_items().msvc_try_filter() {
864 Some(did) => bx.get_static(did),
865 None => bug!("msvc_try_filter not defined"),
867 let funclet = catchpad.catch_pad(cs, &[tydesc, bx.const_i32(0), slot]);
868 let addr = catchpad.load(slot, ptr_align);
870 let i64_align = bx.tcx().data_layout.i64_align.abi;
871 let arg1 = catchpad.load(addr, i64_align);
872 let val1 = bx.const_i32(1);
873 let gep1 = catchpad.inbounds_gep(addr, &[val1]);
874 let arg2 = catchpad.load(gep1, i64_align);
875 let local_ptr = catchpad.bitcast(local_ptr, i64p);
876 let gep2 = catchpad.inbounds_gep(local_ptr, &[val1]);
877 catchpad.store(arg1, local_ptr, i64_align);
878 catchpad.store(arg2, gep2, i64_align);
879 catchpad.catch_ret(&funclet, caught.llbb());
881 caught.ret(bx.const_i32(1));
884 // Note that no invoke is used here because by definition this function
885 // can't panic (that's what it's catching).
886 let ret = bx.call(llfn, &[func, data, local_ptr], None);
887 let i32_align = bx.tcx().data_layout.i32_align.abi;
888 bx.store(ret, dest, i32_align);
891 // Definition of the standard "try" function for Rust using the GNU-like model
892 // of exceptions (e.g., the normal semantics of LLVM's landingpad and invoke
895 // This codegen is a little surprising because we always call a shim
896 // function instead of inlining the call to `invoke` manually here. This is done
897 // because in LLVM we're only allowed to have one personality per function
898 // definition. The call to the `try` intrinsic is being inlined into the
899 // function calling it, and that function may already have other personality
900 // functions in play. By calling a shim we're guaranteed that our shim will have
901 // the right personality function.
903 bx: &mut Builder<'a, 'll, 'tcx>,
906 local_ptr: &'ll Value,
909 let llfn = get_rust_try_fn(bx, &mut |mut bx| {
910 // Codegens the shims described above:
913 // invoke %func(%args...) normal %normal unwind %catch
919 // (ptr, _) = landingpad
920 // store ptr, %local_ptr
923 // Note that the `local_ptr` data passed into the `try` intrinsic is
924 // expected to be `*mut *mut u8` for this to actually work, but that's
925 // managed by the standard library.
927 let mut then = bx.build_sibling_block("then");
928 let mut catch = bx.build_sibling_block("catch");
930 let func = llvm::get_param(bx.llfn(), 0);
931 let data = llvm::get_param(bx.llfn(), 1);
932 let local_ptr = llvm::get_param(bx.llfn(), 2);
933 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
934 then.ret(bx.const_i32(0));
936 // Type indicator for the exception being thrown.
938 // The first value in this tuple is a pointer to the exception object
939 // being thrown. The second value is a "selector" indicating which of
940 // the landing pad clauses the exception's type had been matched to.
941 // rust_try ignores the selector.
942 let lpad_ty = bx.type_struct(&[bx.type_i8p(), bx.type_i32()], false);
943 let vals = catch.landing_pad(lpad_ty, bx.eh_personality(), 1);
944 catch.add_clause(vals, bx.const_null(bx.type_i8p()));
945 let ptr = catch.extract_value(vals, 0);
946 let ptr_align = bx.tcx().data_layout.pointer_align.abi;
947 let bitcast = catch.bitcast(local_ptr, bx.type_ptr_to(bx.type_i8p()));
948 catch.store(ptr, bitcast, ptr_align);
949 catch.ret(bx.const_i32(1));
952 // Note that no invoke is used here because by definition this function
953 // can't panic (that's what it's catching).
954 let ret = bx.call(llfn, &[func, data, local_ptr], None);
955 let i32_align = bx.tcx().data_layout.i32_align.abi;
956 bx.store(ret, dest, i32_align);
959 // Helper function to give a Block to a closure to codegen a shim function.
960 // This is currently primarily used for the `try` intrinsic functions above.
961 fn gen_fn<'ll, 'tcx>(
962 cx: &CodegenCx<'ll, 'tcx>,
964 inputs: Vec<Ty<'tcx>>,
966 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
968 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
972 hir::Unsafety::Unsafe,
975 let llfn = cx.define_internal_fn(name, rust_fn_sig);
976 attributes::from_fn_attrs(cx, llfn, None, rust_fn_sig);
977 let bx = Builder::new_block(cx, llfn, "entry-block");
982 // Helper function used to get a handle to the `__rust_try` function used to
985 // This function is only generated once and is then cached.
986 fn get_rust_try_fn<'ll, 'tcx>(
987 cx: &CodegenCx<'ll, 'tcx>,
988 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
990 if let Some(llfn) = cx.rust_try_fn.get() {
994 // Define the type up front for the signature of the rust_try function.
996 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
997 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1001 hir::Unsafety::Unsafe,
1004 let output = tcx.types.i32;
1005 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1006 cx.rust_try_fn.set(Some(rust_try));
1010 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1011 span_err!(a, b, E0511, "{}", c);
1014 fn generic_simd_intrinsic(
1015 bx: &mut Builder<'a, 'll, 'tcx>,
1017 callee_ty: Ty<'tcx>,
1018 args: &[OperandRef<'tcx, &'ll Value>],
1020 llret_ty: &'ll Type,
1022 ) -> Result<&'ll Value, ()> {
1023 // macros for error handling:
1024 macro_rules! emit_error {
1028 ($msg: tt, $($fmt: tt)*) => {
1029 span_invalid_monomorphization_error(
1031 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1036 macro_rules! return_error {
1039 emit_error!($($fmt)*);
1045 macro_rules! require {
1046 ($cond: expr, $($fmt: tt)*) => {
1048 return_error!($($fmt)*);
1053 macro_rules! require_simd {
1054 ($ty: expr, $position: expr) => {
1055 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1060 let sig = tcx.normalize_erasing_late_bound_regions(
1061 ty::ParamEnv::reveal_all(),
1062 &callee_ty.fn_sig(tcx),
1064 let arg_tys = sig.inputs();
1066 if name == "simd_select_bitmask" {
1067 let in_ty = arg_tys[0];
1068 let m_len = match in_ty.sty {
1069 // Note that this `.unwrap()` crashes for isize/usize, that's sort
1070 // of intentional as there's not currently a use case for that.
1071 ty::Int(i) => i.bit_width().unwrap(),
1072 ty::Uint(i) => i.bit_width().unwrap(),
1073 _ => return_error!("`{}` is not an integral type", in_ty),
1075 require_simd!(arg_tys[1], "argument");
1076 let v_len = arg_tys[1].simd_size(tcx);
1077 require!(m_len == v_len,
1078 "mismatched lengths: mask length `{}` != other vector length `{}`",
1081 let i1 = bx.type_i1();
1082 let i1xn = bx.type_vector(i1, m_len as u64);
1083 let m_i1s = bx.bitcast(args[0].immediate(), i1xn);
1084 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1087 // every intrinsic below takes a SIMD vector as its first argument
1088 require_simd!(arg_tys[0], "input");
1089 let in_ty = arg_tys[0];
1090 let in_elem = arg_tys[0].simd_type(tcx);
1091 let in_len = arg_tys[0].simd_size(tcx);
1093 let comparison = match name {
1094 "simd_eq" => Some(hir::BinOpKind::Eq),
1095 "simd_ne" => Some(hir::BinOpKind::Ne),
1096 "simd_lt" => Some(hir::BinOpKind::Lt),
1097 "simd_le" => Some(hir::BinOpKind::Le),
1098 "simd_gt" => Some(hir::BinOpKind::Gt),
1099 "simd_ge" => Some(hir::BinOpKind::Ge),
1103 if let Some(cmp_op) = comparison {
1104 require_simd!(ret_ty, "return");
1106 let out_len = ret_ty.simd_size(tcx);
1107 require!(in_len == out_len,
1108 "expected return type with length {} (same as input type `{}`), \
1109 found `{}` with length {}",
1112 require!(bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer,
1113 "expected return type with integer elements, found `{}` with non-integer `{}`",
1115 ret_ty.simd_type(tcx));
1117 return Ok(compare_simd_types(bx,
1118 args[0].immediate(),
1119 args[1].immediate(),
1125 if name.starts_with("simd_shuffle") {
1126 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1127 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1129 require_simd!(ret_ty, "return");
1131 let out_len = ret_ty.simd_size(tcx);
1132 require!(out_len == n,
1133 "expected return type of length {}, found `{}` with length {}",
1134 n, ret_ty, out_len);
1135 require!(in_elem == ret_ty.simd_type(tcx),
1136 "expected return element type `{}` (element of input `{}`), \
1137 found `{}` with element type `{}`",
1139 ret_ty, ret_ty.simd_type(tcx));
1141 let total_len = in_len as u128 * 2;
1143 let vector = args[2].immediate();
1145 let indices: Option<Vec<_>> = (0..n)
1148 let val = bx.const_get_elt(vector, i as u64);
1149 match bx.const_to_opt_u128(val, true) {
1151 emit_error!("shuffle index #{} is not a constant", arg_idx);
1154 Some(idx) if idx >= total_len => {
1155 emit_error!("shuffle index #{} is out of bounds (limit {})",
1156 arg_idx, total_len);
1159 Some(idx) => Some(bx.const_i32(idx as i32)),
1163 let indices = match indices {
1165 None => return Ok(bx.const_null(llret_ty))
1168 return Ok(bx.shuffle_vector(args[0].immediate(),
1169 args[1].immediate(),
1170 bx.const_vector(&indices)))
1173 if name == "simd_insert" {
1174 require!(in_elem == arg_tys[2],
1175 "expected inserted type `{}` (element of input `{}`), found `{}`",
1176 in_elem, in_ty, arg_tys[2]);
1177 return Ok(bx.insert_element(args[0].immediate(),
1178 args[2].immediate(),
1179 args[1].immediate()))
1181 if name == "simd_extract" {
1182 require!(ret_ty == in_elem,
1183 "expected return type `{}` (element of input `{}`), found `{}`",
1184 in_elem, in_ty, ret_ty);
1185 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1188 if name == "simd_select" {
1189 let m_elem_ty = in_elem;
1191 require_simd!(arg_tys[1], "argument");
1192 let v_len = arg_tys[1].simd_size(tcx);
1193 require!(m_len == v_len,
1194 "mismatched lengths: mask length `{}` != other vector length `{}`",
1197 match m_elem_ty.sty {
1199 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1201 // truncate the mask to a vector of i1s
1202 let i1 = bx.type_i1();
1203 let i1xn = bx.type_vector(i1, m_len as u64);
1204 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1205 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1208 if name == "simd_bitmask" {
1209 // The `fn simd_bitmask(vector) -> unsigned integer` intrinsic takes a
1210 // vector mask and returns an unsigned integer containing the most
1211 // significant bit (MSB) of each lane.
1212 use rustc_target::abi::HasDataLayout;
1214 // If the vector has less than 8 lanes, an u8 is returned with zeroed
1216 let expected_int_bits = in_len.max(8);
1218 ty::Uint(i) if i.bit_width() == Some(expected_int_bits) => (),
1220 "bitmask `{}`, expected `u{}`",
1221 ret_ty, expected_int_bits
1225 // Integer vector <i{in_bitwidth} x in_len>:
1226 let (i_xn, in_elem_bitwidth) = match in_elem.sty {
1228 args[0].immediate(),
1229 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1232 args[0].immediate(),
1233 i.bit_width().unwrap_or(bx.data_layout().pointer_size.bits() as _)
1236 "vector argument `{}`'s element type `{}`, expected integer element type",
1241 // Shift the MSB to the right by "in_elem_bitwidth - 1" into the first bit position.
1242 let shift_indices = vec![
1243 bx.cx.const_int(bx.type_ix(in_elem_bitwidth as _), (in_elem_bitwidth - 1) as _); in_len
1245 let i_xn_msb = bx.lshr(i_xn, bx.const_vector(shift_indices.as_slice()));
1246 // Truncate vector to an <i1 x N>
1247 let i1xn = bx.trunc(i_xn_msb, bx.type_vector(bx.type_i1(), in_len as _));
1248 // Bitcast <i1 x N> to iN:
1249 let i_ = bx.bitcast(i1xn, bx.type_ix(in_len as _));
1250 // Zero-extend iN to the bitmask type:
1251 return Ok(bx.zext(i_, bx.type_ix(expected_int_bits as _)));
1254 fn simd_simple_float_intrinsic(
1256 in_elem: &::rustc::ty::TyS,
1257 in_ty: &::rustc::ty::TyS,
1259 bx: &mut Builder<'a, 'll, 'tcx>,
1261 args: &[OperandRef<'tcx, &'ll Value>],
1262 ) -> Result<&'ll Value, ()> {
1263 macro_rules! emit_error {
1267 ($msg: tt, $($fmt: tt)*) => {
1268 span_invalid_monomorphization_error(
1270 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1274 macro_rules! return_error {
1277 emit_error!($($fmt)*);
1282 let ety = match in_elem.sty {
1283 ty::Float(f) if f.bit_width() == 32 => {
1284 if in_len < 2 || in_len > 16 {
1286 "unsupported floating-point vector `{}` with length `{}` \
1287 out-of-range [2, 16]",
1292 ty::Float(f) if f.bit_width() == 64 => {
1293 if in_len < 2 || in_len > 8 {
1294 return_error!("unsupported floating-point vector `{}` with length `{}` \
1295 out-of-range [2, 8]",
1301 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1305 return_error!("`{}` is not a floating-point type", in_ty);
1309 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1310 let intrinsic = bx.get_intrinsic(&llvm_name);
1311 let c = bx.call(intrinsic,
1312 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1314 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1320 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1323 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1326 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1329 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1332 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1335 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1338 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1341 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1344 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1347 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1350 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1353 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1356 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1359 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1361 _ => { /* fallthrough */ }
1365 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1366 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1367 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1368 let p0s: String = "p0".repeat(no_pointers);
1370 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1371 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1372 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1373 _ => unreachable!(),
1377 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1378 mut no_pointers: usize) -> &'ll Type {
1379 // FIXME: use cx.layout_of(ty).llvm_type() ?
1380 let mut elem_ty = match elem_ty.sty {
1381 ty::Int(v) => cx.type_int_from_ty( v),
1382 ty::Uint(v) => cx.type_uint_from_ty( v),
1383 ty::Float(v) => cx.type_float_from_ty( v),
1384 _ => unreachable!(),
1386 while no_pointers > 0 {
1387 elem_ty = cx.type_ptr_to(elem_ty);
1390 cx.type_vector(elem_ty, vec_len as u64)
1394 if name == "simd_gather" {
1395 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1396 // mask: <N x i{M}>) -> <N x T>
1397 // * N: number of elements in the input vectors
1398 // * T: type of the element to load
1399 // * M: any integer width is supported, will be truncated to i1
1401 // All types must be simd vector types
1402 require_simd!(in_ty, "first");
1403 require_simd!(arg_tys[1], "second");
1404 require_simd!(arg_tys[2], "third");
1405 require_simd!(ret_ty, "return");
1407 // Of the same length:
1408 require!(in_len == arg_tys[1].simd_size(tcx),
1409 "expected {} argument with length {} (same as input type `{}`), \
1410 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1411 arg_tys[1].simd_size(tcx));
1412 require!(in_len == arg_tys[2].simd_size(tcx),
1413 "expected {} argument with length {} (same as input type `{}`), \
1414 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1415 arg_tys[2].simd_size(tcx));
1417 // The return type must match the first argument type
1418 require!(ret_ty == in_ty,
1419 "expected return type `{}`, found `{}`",
1422 // This counts how many pointers
1423 fn ptr_count(t: ty::Ty) -> usize {
1425 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1431 fn non_ptr(t: ty::Ty) -> ty::Ty {
1433 ty::RawPtr(p) => non_ptr(p.ty),
1438 // The second argument must be a simd vector with an element type that's a pointer
1439 // to the element type of the first argument
1440 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1441 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1442 non_ptr(arg_tys[1].simd_type(tcx))),
1444 require!(false, "expected element type `{}` of second argument `{}` \
1445 to be a pointer to the element type `{}` of the first \
1446 argument `{}`, found `{}` != `*_ {}`",
1447 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1448 arg_tys[1].simd_type(tcx).sty, in_elem);
1452 assert!(pointer_count > 0);
1453 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1454 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1456 // The element type of the third argument must be a signed integer type of any width:
1457 match arg_tys[2].simd_type(tcx).sty {
1460 require!(false, "expected element type `{}` of third argument `{}` \
1461 to be a signed integer type",
1462 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1466 // Alignment of T, must be a constant integer value:
1467 let alignment_ty = bx.type_i32();
1468 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1470 // Truncate the mask vector to a vector of i1s:
1471 let (mask, mask_ty) = {
1472 let i1 = bx.type_i1();
1473 let i1xn = bx.type_vector(i1, in_len as u64);
1474 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1477 // Type of the vector of pointers:
1478 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1479 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1481 // Type of the vector of elements:
1482 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1483 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1485 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1486 llvm_elem_vec_str, llvm_pointer_vec_str);
1487 let f = bx.declare_cfn(&llvm_intrinsic,
1489 llvm_pointer_vec_ty,
1492 llvm_elem_vec_ty], llvm_elem_vec_ty));
1493 llvm::SetUnnamedAddr(f, false);
1494 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1499 if name == "simd_scatter" {
1500 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1501 // mask: <N x i{M}>) -> ()
1502 // * N: number of elements in the input vectors
1503 // * T: type of the element to load
1504 // * M: any integer width is supported, will be truncated to i1
1506 // All types must be simd vector types
1507 require_simd!(in_ty, "first");
1508 require_simd!(arg_tys[1], "second");
1509 require_simd!(arg_tys[2], "third");
1511 // Of the same length:
1512 require!(in_len == arg_tys[1].simd_size(tcx),
1513 "expected {} argument with length {} (same as input type `{}`), \
1514 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1515 arg_tys[1].simd_size(tcx));
1516 require!(in_len == arg_tys[2].simd_size(tcx),
1517 "expected {} argument with length {} (same as input type `{}`), \
1518 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1519 arg_tys[2].simd_size(tcx));
1521 // This counts how many pointers
1522 fn ptr_count(t: ty::Ty) -> usize {
1524 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1530 fn non_ptr(t: ty::Ty) -> ty::Ty {
1532 ty::RawPtr(p) => non_ptr(p.ty),
1537 // The second argument must be a simd vector with an element type that's a pointer
1538 // to the element type of the first argument
1539 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1540 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1541 => (ptr_count(arg_tys[1].simd_type(tcx)),
1542 non_ptr(arg_tys[1].simd_type(tcx))),
1544 require!(false, "expected element type `{}` of second argument `{}` \
1545 to be a pointer to the element type `{}` of the first \
1546 argument `{}`, found `{}` != `*mut {}`",
1547 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1548 arg_tys[1].simd_type(tcx).sty, in_elem);
1552 assert!(pointer_count > 0);
1553 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1554 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1556 // The element type of the third argument must be a signed integer type of any width:
1557 match arg_tys[2].simd_type(tcx).sty {
1560 require!(false, "expected element type `{}` of third argument `{}` \
1561 to be a signed integer type",
1562 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1566 // Alignment of T, must be a constant integer value:
1567 let alignment_ty = bx.type_i32();
1568 let alignment = bx.const_i32(bx.align_of(in_elem).bytes() as i32);
1570 // Truncate the mask vector to a vector of i1s:
1571 let (mask, mask_ty) = {
1572 let i1 = bx.type_i1();
1573 let i1xn = bx.type_vector(i1, in_len as u64);
1574 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1577 let ret_t = bx.type_void();
1579 // Type of the vector of pointers:
1580 let llvm_pointer_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count);
1581 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1583 // Type of the vector of elements:
1584 let llvm_elem_vec_ty = llvm_vector_ty(bx, underlying_ty, in_len, pointer_count - 1);
1585 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1587 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1588 llvm_elem_vec_str, llvm_pointer_vec_str);
1589 let f = bx.declare_cfn(&llvm_intrinsic,
1590 bx.type_func(&[llvm_elem_vec_ty,
1591 llvm_pointer_vec_ty,
1594 llvm::SetUnnamedAddr(f, false);
1595 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1600 macro_rules! arith_red {
1601 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1603 require!(ret_ty == in_elem,
1604 "expected return type `{}` (element of input `{}`), found `{}`",
1605 in_elem, in_ty, ret_ty);
1606 return match in_elem.sty {
1607 ty::Int(_) | ty::Uint(_) => {
1608 let r = bx.$integer_reduce(args[0].immediate());
1610 // if overflow occurs, the result is the
1611 // mathematical result modulo 2^n:
1612 if name.contains("mul") {
1613 Ok(bx.mul(args[1].immediate(), r))
1615 Ok(bx.add(args[1].immediate(), r))
1618 Ok(bx.$integer_reduce(args[0].immediate()))
1622 // ordered arithmetic reductions take an accumulator
1623 let acc = if $ordered {
1624 let acc = args[1].immediate();
1625 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1626 // * if the accumulator of the fadd isn't 0, incorrect
1627 // code is generated
1628 // * if the accumulator of the fmul isn't 1, incorrect
1629 // code is generated
1630 match bx.const_get_real(acc) {
1631 None => return_error!("accumulator of {} is not a constant", $name),
1632 Some((v, loses_info)) => {
1633 if $name.contains("mul") && v != 1.0_f64 {
1634 return_error!("accumulator of {} is not 1.0", $name);
1635 } else if $name.contains("add") && v != 0.0_f64 {
1636 return_error!("accumulator of {} is not 0.0", $name);
1637 } else if loses_info {
1638 return_error!("accumulator of {} loses information", $name);
1644 // unordered arithmetic reductions do not:
1645 match f.bit_width() {
1646 32 => bx.const_undef(bx.type_f32()),
1647 64 => bx.const_undef(bx.type_f64()),
1650 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1651 $name, in_ty, in_elem, v, ret_ty
1656 Ok(bx.$float_reduce(acc, args[0].immediate()))
1660 "unsupported {} from `{}` with element `{}` to `{}`",
1661 $name, in_ty, in_elem, ret_ty
1669 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1670 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1671 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1672 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1674 macro_rules! minmax_red {
1675 ($name:tt: $int_red:ident, $float_red:ident) => {
1677 require!(ret_ty == in_elem,
1678 "expected return type `{}` (element of input `{}`), found `{}`",
1679 in_elem, in_ty, ret_ty);
1680 return match in_elem.sty {
1682 Ok(bx.$int_red(args[0].immediate(), true))
1685 Ok(bx.$int_red(args[0].immediate(), false))
1688 Ok(bx.$float_red(args[0].immediate()))
1691 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1692 $name, in_ty, in_elem, ret_ty)
1700 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1701 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1703 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1704 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1706 macro_rules! bitwise_red {
1707 ($name:tt : $red:ident, $boolean:expr) => {
1709 let input = if !$boolean {
1710 require!(ret_ty == in_elem,
1711 "expected return type `{}` (element of input `{}`), found `{}`",
1712 in_elem, in_ty, ret_ty);
1716 ty::Int(_) | ty::Uint(_) => {},
1718 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1719 $name, in_ty, in_elem, ret_ty)
1723 // boolean reductions operate on vectors of i1s:
1724 let i1 = bx.type_i1();
1725 let i1xn = bx.type_vector(i1, in_len as u64);
1726 bx.trunc(args[0].immediate(), i1xn)
1728 return match in_elem.sty {
1729 ty::Int(_) | ty::Uint(_) => {
1730 let r = bx.$red(input);
1735 bx.zext(r, bx.type_bool())
1740 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1741 $name, in_ty, in_elem, ret_ty)
1748 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1749 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1750 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1751 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1752 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1754 if name == "simd_cast" {
1755 require_simd!(ret_ty, "return");
1756 let out_len = ret_ty.simd_size(tcx);
1757 require!(in_len == out_len,
1758 "expected return type with length {} (same as input type `{}`), \
1759 found `{}` with length {}",
1762 // casting cares about nominal type, not just structural type
1763 let out_elem = ret_ty.simd_type(tcx);
1765 if in_elem == out_elem { return Ok(args[0].immediate()); }
1767 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1769 let (in_style, in_width) = match in_elem.sty {
1770 // vectors of pointer-sized integers should've been
1771 // disallowed before here, so this unwrap is safe.
1772 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1773 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1774 ty::Float(f) => (Style::Float, f.bit_width()),
1775 _ => (Style::Unsupported, 0)
1777 let (out_style, out_width) = match out_elem.sty {
1778 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1779 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1780 ty::Float(f) => (Style::Float, f.bit_width()),
1781 _ => (Style::Unsupported, 0)
1784 match (in_style, out_style) {
1785 (Style::Int(in_is_signed), Style::Int(_)) => {
1786 return Ok(match in_width.cmp(&out_width) {
1787 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1788 Ordering::Equal => args[0].immediate(),
1789 Ordering::Less => if in_is_signed {
1790 bx.sext(args[0].immediate(), llret_ty)
1792 bx.zext(args[0].immediate(), llret_ty)
1796 (Style::Int(in_is_signed), Style::Float) => {
1797 return Ok(if in_is_signed {
1798 bx.sitofp(args[0].immediate(), llret_ty)
1800 bx.uitofp(args[0].immediate(), llret_ty)
1803 (Style::Float, Style::Int(out_is_signed)) => {
1804 return Ok(if out_is_signed {
1805 bx.fptosi(args[0].immediate(), llret_ty)
1807 bx.fptoui(args[0].immediate(), llret_ty)
1810 (Style::Float, Style::Float) => {
1811 return Ok(match in_width.cmp(&out_width) {
1812 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1813 Ordering::Equal => args[0].immediate(),
1814 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1817 _ => {/* Unsupported. Fallthrough. */}
1820 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1824 macro_rules! arith {
1825 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1826 $(if name == stringify!($name) {
1828 $($(ty::$p(_))|* => {
1829 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1834 "unsupported operation on `{}` with element `{}`",
1841 simd_add: Uint, Int => add, Float => fadd;
1842 simd_sub: Uint, Int => sub, Float => fsub;
1843 simd_mul: Uint, Int => mul, Float => fmul;
1844 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1845 simd_rem: Uint => urem, Int => srem, Float => frem;
1846 simd_shl: Uint, Int => shl;
1847 simd_shr: Uint => lshr, Int => ashr;
1848 simd_and: Uint, Int => and;
1849 simd_or: Uint, Int => or;
1850 simd_xor: Uint, Int => xor;
1851 simd_fmax: Float => maxnum;
1852 simd_fmin: Float => minnum;
1854 span_bug!(span, "unknown SIMD intrinsic");
1857 // Returns the width of an int Ty, and if it's signed or not
1858 // Returns None if the type is not an integer
1859 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1861 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1863 ty::Int(t) => Some((match t {
1864 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1865 ast::IntTy::I8 => 8,
1866 ast::IntTy::I16 => 16,
1867 ast::IntTy::I32 => 32,
1868 ast::IntTy::I64 => 64,
1869 ast::IntTy::I128 => 128,
1871 ty::Uint(t) => Some((match t {
1872 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1873 ast::UintTy::U8 => 8,
1874 ast::UintTy::U16 => 16,
1875 ast::UintTy::U32 => 32,
1876 ast::UintTy::U64 => 64,
1877 ast::UintTy::U128 => 128,
1883 // Returns the width of a float TypeVariant
1884 // Returns None if the type is not a float
1885 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1887 ty::Float(t) => Some(t.bit_width() as u64),