1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_upper_case_globals)]
14 use intrinsics::{self, Intrinsic};
17 use abi::{Abi, FnType, LlvmType, PassMode};
18 use mir::place::PlaceRef;
19 use mir::operand::{OperandRef, OperandValue};
22 use context::CodegenCx;
26 use type_of::LayoutLlvmExt;
27 use rustc::ty::{self, Ty};
28 use rustc::ty::layout::LayoutOf;
31 use syntax::symbol::Symbol;
36 BuilderMethods, ConstMethods, BaseTypeMethods, DerivedTypeMethods, DerivedIntrinsicMethods,
39 use rustc::session::Session;
42 use std::cmp::Ordering;
45 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
46 let llvm_name = match name {
47 "sqrtf32" => "llvm.sqrt.f32",
48 "sqrtf64" => "llvm.sqrt.f64",
49 "powif32" => "llvm.powi.f32",
50 "powif64" => "llvm.powi.f64",
51 "sinf32" => "llvm.sin.f32",
52 "sinf64" => "llvm.sin.f64",
53 "cosf32" => "llvm.cos.f32",
54 "cosf64" => "llvm.cos.f64",
55 "powf32" => "llvm.pow.f32",
56 "powf64" => "llvm.pow.f64",
57 "expf32" => "llvm.exp.f32",
58 "expf64" => "llvm.exp.f64",
59 "exp2f32" => "llvm.exp2.f32",
60 "exp2f64" => "llvm.exp2.f64",
61 "logf32" => "llvm.log.f32",
62 "logf64" => "llvm.log.f64",
63 "log10f32" => "llvm.log10.f32",
64 "log10f64" => "llvm.log10.f64",
65 "log2f32" => "llvm.log2.f32",
66 "log2f64" => "llvm.log2.f64",
67 "fmaf32" => "llvm.fma.f32",
68 "fmaf64" => "llvm.fma.f64",
69 "fabsf32" => "llvm.fabs.f32",
70 "fabsf64" => "llvm.fabs.f64",
71 "copysignf32" => "llvm.copysign.f32",
72 "copysignf64" => "llvm.copysign.f64",
73 "floorf32" => "llvm.floor.f32",
74 "floorf64" => "llvm.floor.f64",
75 "ceilf32" => "llvm.ceil.f32",
76 "ceilf64" => "llvm.ceil.f64",
77 "truncf32" => "llvm.trunc.f32",
78 "truncf64" => "llvm.trunc.f64",
79 "rintf32" => "llvm.rint.f32",
80 "rintf64" => "llvm.rint.f64",
81 "nearbyintf32" => "llvm.nearbyint.f32",
82 "nearbyintf64" => "llvm.nearbyint.f64",
83 "roundf32" => "llvm.round.f32",
84 "roundf64" => "llvm.round.f64",
85 "assume" => "llvm.assume",
86 "abort" => "llvm.trap",
89 Some(cx.get_intrinsic(&llvm_name))
92 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
93 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
94 /// add them to librustc_codegen_llvm/context.rs
95 pub fn codegen_intrinsic_call(
96 bx: &Builder<'a, 'll, 'tcx>,
98 fn_ty: &FnType<'tcx, Ty<'tcx>>,
99 args: &[OperandRef<'tcx, &'ll Value>],
100 llresult: &'ll Value,
106 let (def_id, substs) = match callee_ty.sty {
107 ty::FnDef(def_id, substs) => (def_id, substs),
108 _ => bug!("expected fn item type, found {}", callee_ty)
111 let sig = callee_ty.fn_sig(tcx);
112 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
113 let arg_tys = sig.inputs();
114 let ret_ty = sig.output();
115 let name = &*tcx.item_name(def_id).as_str();
117 let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
118 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
120 let simple = get_simple_intrinsic(cx, name);
121 let llval = match name {
122 _ if simple.is_some() => {
123 bx.call(simple.unwrap(),
124 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
131 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
132 bx.call(expect, &[args[0].immediate(), bx.cx().const_bool(true)], None)
135 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
136 bx.call(expect, &[args[0].immediate(), bx.cx().const_bool(false)], None)
139 try_intrinsic(bx, cx,
147 let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
148 bx.call(llfn, &[], None)
151 let tp_ty = substs.type_at(0);
152 cx.const_usize(cx.size_of(tp_ty).bytes())
155 let tp_ty = substs.type_at(0);
156 if let OperandValue::Pair(_, meta) = args[0].val {
158 glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
161 cx.const_usize(cx.size_of(tp_ty).bytes())
165 let tp_ty = substs.type_at(0);
166 cx.const_usize(cx.align_of(tp_ty).abi())
168 "min_align_of_val" => {
169 let tp_ty = substs.type_at(0);
170 if let OperandValue::Pair(_, meta) = args[0].val {
172 glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
175 cx.const_usize(cx.align_of(tp_ty).abi())
179 let tp_ty = substs.type_at(0);
180 cx.const_usize(cx.align_of(tp_ty).pref())
183 let tp_ty = substs.type_at(0);
184 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
185 cx.const_str_slice(ty_name)
188 cx.const_u64(cx.tcx.type_id_hash(substs.type_at(0)))
191 let ty = substs.type_at(0);
192 if !cx.layout_of(ty).is_zst() {
193 // Just zero out the stack slot.
194 // If we store a zero constant, LLVM will drown in vreg allocation for large data
195 // structures, and the generated code will be awful. (A telltale sign of this is
196 // large quantities of `mov [byte ptr foo],0` in the generated code.)
208 // Effectively no-ops
209 "uninit" | "forget" => {
213 let tp_ty = substs.type_at(0);
215 cx.const_bool(bx.cx().type_needs_drop(tp_ty))
218 let ptr = args[0].immediate();
219 let offset = args[1].immediate();
220 bx.inbounds_gep(ptr, &[offset])
223 let ptr = args[0].immediate();
224 let offset = args[1].immediate();
225 bx.gep(ptr, &[offset])
228 "copy_nonoverlapping" => {
229 copy_intrinsic(bx, false, false, substs.type_at(0),
230 args[1].immediate(), args[0].immediate(), args[2].immediate())
233 copy_intrinsic(bx, true, false, substs.type_at(0),
234 args[1].immediate(), args[0].immediate(), args[2].immediate())
237 memset_intrinsic(bx, false, substs.type_at(0),
238 args[0].immediate(), args[1].immediate(), args[2].immediate())
241 "volatile_copy_nonoverlapping_memory" => {
242 copy_intrinsic(bx, false, true, substs.type_at(0),
243 args[0].immediate(), args[1].immediate(), args[2].immediate())
245 "volatile_copy_memory" => {
246 copy_intrinsic(bx, true, true, substs.type_at(0),
247 args[0].immediate(), args[1].immediate(), args[2].immediate())
249 "volatile_set_memory" => {
250 memset_intrinsic(bx, true, substs.type_at(0),
251 args[0].immediate(), args[1].immediate(), args[2].immediate())
253 "volatile_load" | "unaligned_volatile_load" => {
254 let tp_ty = substs.type_at(0);
255 let mut ptr = args[0].immediate();
256 if let PassMode::Cast(ty) = fn_ty.ret.mode {
257 ptr = bx.pointercast(ptr, bx.cx().type_ptr_to(ty.llvm_type(cx)));
259 let load = bx.volatile_load(ptr);
260 let align = if name == "unaligned_volatile_load" {
263 cx.align_of(tp_ty).abi() as u32
266 llvm::LLVMSetAlignment(load, align);
268 to_immediate(bx, load, cx.layout_of(tp_ty))
270 "volatile_store" => {
271 let dst = args[0].deref(bx.cx());
272 args[1].val.volatile_store(bx, dst);
275 "unaligned_volatile_store" => {
276 let dst = args[0].deref(bx.cx());
277 args[1].val.unaligned_volatile_store(bx, dst);
280 "prefetch_read_data" | "prefetch_write_data" |
281 "prefetch_read_instruction" | "prefetch_write_instruction" => {
282 let expect = cx.get_intrinsic(&("llvm.prefetch"));
283 let (rw, cache_type) = match name {
284 "prefetch_read_data" => (0, 1),
285 "prefetch_write_data" => (1, 1),
286 "prefetch_read_instruction" => (0, 0),
287 "prefetch_write_instruction" => (1, 0),
294 cx.const_i32(cache_type)
297 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
298 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
299 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
300 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
301 "rotate_left" | "rotate_right" => {
303 match int_type_width_signed(ty, cx) {
304 Some((width, signed)) =>
307 let y = cx.const_bool(false);
308 let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
309 bx.call(llfn, &[args[0].immediate(), y], None)
311 "ctlz_nonzero" | "cttz_nonzero" => {
312 let y = cx.const_bool(true);
313 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
314 let llfn = cx.get_intrinsic(llvm_name);
315 bx.call(llfn, &[args[0].immediate(), y], None)
317 "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
318 &[args[0].immediate()], None),
321 args[0].immediate() // byte swap a u8/i8 is just a no-op
323 bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
324 &[args[0].immediate()], None)
328 bx.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
329 &[args[0].immediate()], None)
331 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
332 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
333 if signed { 's' } else { 'u' },
335 let llfn = bx.cx().get_intrinsic(&intrinsic);
337 // Convert `i1` to a `bool`, and write it to the out parameter
338 let pair = bx.call(llfn, &[
342 let val = bx.extract_value(pair, 0);
343 let overflow = bx.zext(bx.extract_value(pair, 1), cx.type_bool());
345 let dest = result.project_field(bx, 0);
346 bx.store(val, dest.llval, dest.align);
347 let dest = result.project_field(bx, 1);
348 bx.store(overflow, dest.llval, dest.align);
352 "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()),
353 "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()),
354 "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()),
357 bx.exactsdiv(args[0].immediate(), args[1].immediate())
359 bx.exactudiv(args[0].immediate(), args[1].immediate())
363 bx.sdiv(args[0].immediate(), args[1].immediate())
365 bx.udiv(args[0].immediate(), args[1].immediate())
369 bx.srem(args[0].immediate(), args[1].immediate())
371 bx.urem(args[0].immediate(), args[1].immediate())
373 "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()),
376 bx.ashr(args[0].immediate(), args[1].immediate())
378 bx.lshr(args[0].immediate(), args[1].immediate())
380 "rotate_left" | "rotate_right" => {
381 let is_left = name == "rotate_left";
382 let val = args[0].immediate();
383 let raw_shift = args[1].immediate();
384 if llvm_util::get_major_version() >= 7 {
385 // rotate = funnel shift with first two args the same
386 let llvm_name = &format!("llvm.fsh{}.i{}",
387 if is_left { 'l' } else { 'r' }, width);
388 let llfn = cx.get_intrinsic(llvm_name);
389 bx.call(llfn, &[val, val, raw_shift], None)
391 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
392 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
393 let width = cx.const_uint(cx.type_ix(width), width);
394 let shift = bx.urem(raw_shift, width);
395 let inv_shift = bx.urem(bx.sub(width, raw_shift), width);
396 let shift1 = bx.shl(val, if is_left { shift } else { inv_shift });
397 let shift2 = bx.lshr(val, if !is_left { shift } else { inv_shift });
398 bx.or(shift1, shift2)
404 span_invalid_monomorphization_error(
406 &format!("invalid monomorphization of `{}` intrinsic: \
407 expected basic integer type, found `{}`", name, ty));
412 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
413 let sty = &arg_tys[0].sty;
414 match float_type_width(sty) {
417 "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
418 "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
419 "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
420 "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
421 "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()),
425 span_invalid_monomorphization_error(
427 &format!("invalid monomorphization of `{}` intrinsic: \
428 expected basic float type, found `{}`", name, sty));
435 "discriminant_value" => {
436 args[0].deref(bx.cx()).codegen_get_discr(bx, ret_ty)
439 name if name.starts_with("simd_") => {
440 match generic_simd_intrinsic(bx, name,
449 // This requires that atomic intrinsics follow a specific naming pattern:
450 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
451 name if name.starts_with("atomic_") => {
452 use self::AtomicOrdering::*;
454 let split: Vec<&str> = name.split('_').collect();
456 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
457 let (order, failorder) = match split.len() {
458 2 => (SequentiallyConsistent, SequentiallyConsistent),
459 3 => match split[2] {
460 "unordered" => (Unordered, Unordered),
461 "relaxed" => (Monotonic, Monotonic),
462 "acq" => (Acquire, Acquire),
463 "rel" => (Release, Monotonic),
464 "acqrel" => (AcquireRelease, Acquire),
465 "failrelaxed" if is_cxchg =>
466 (SequentiallyConsistent, Monotonic),
467 "failacq" if is_cxchg =>
468 (SequentiallyConsistent, Acquire),
469 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
471 4 => match (split[2], split[3]) {
472 ("acq", "failrelaxed") if is_cxchg =>
473 (Acquire, Monotonic),
474 ("acqrel", "failrelaxed") if is_cxchg =>
475 (AcquireRelease, Monotonic),
476 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
478 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
481 let invalid_monomorphization = |ty| {
482 span_invalid_monomorphization_error(tcx.sess, span,
483 &format!("invalid monomorphization of `{}` intrinsic: \
484 expected basic integer type, found `{}`", name, ty));
488 "cxchg" | "cxchgweak" => {
489 let ty = substs.type_at(0);
490 if int_type_width_signed(ty, cx).is_some() {
491 let weak = split[1] == "cxchgweak";
492 let pair = bx.atomic_cmpxchg(
499 let val = bx.extract_value(pair, 0);
500 let success = bx.zext(bx.extract_value(pair, 1), bx.cx().type_bool());
502 let dest = result.project_field(bx, 0);
503 bx.store(val, dest.llval, dest.align);
504 let dest = result.project_field(bx, 1);
505 bx.store(success, dest.llval, dest.align);
508 return invalid_monomorphization(ty);
513 let ty = substs.type_at(0);
514 if int_type_width_signed(ty, cx).is_some() {
515 let size = cx.size_of(ty);
516 bx.atomic_load(args[0].immediate(), order, size)
518 return invalid_monomorphization(ty);
523 let ty = substs.type_at(0);
524 if int_type_width_signed(ty, cx).is_some() {
525 let size = cx.size_of(ty);
526 bx.atomic_store(args[1].immediate(), args[0].immediate(), order, size);
529 return invalid_monomorphization(ty);
534 bx.atomic_fence(order, SynchronizationScope::CrossThread);
538 "singlethreadfence" => {
539 bx.atomic_fence(order, SynchronizationScope::SingleThread);
543 // These are all AtomicRMW ops
545 let atom_op = match op {
546 "xchg" => AtomicRmwBinOp::AtomicXchg,
547 "xadd" => AtomicRmwBinOp::AtomicAdd,
548 "xsub" => AtomicRmwBinOp::AtomicSub,
549 "and" => AtomicRmwBinOp::AtomicAnd,
550 "nand" => AtomicRmwBinOp::AtomicNand,
551 "or" => AtomicRmwBinOp::AtomicOr,
552 "xor" => AtomicRmwBinOp::AtomicXor,
553 "max" => AtomicRmwBinOp::AtomicMax,
554 "min" => AtomicRmwBinOp::AtomicMin,
555 "umax" => AtomicRmwBinOp::AtomicUMax,
556 "umin" => AtomicRmwBinOp::AtomicUMin,
557 _ => cx.sess().fatal("unknown atomic operation")
560 let ty = substs.type_at(0);
561 if int_type_width_signed(ty, cx).is_some() {
562 bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order)
564 return invalid_monomorphization(ty);
570 "nontemporal_store" => {
571 let dst = args[0].deref(bx.cx());
572 args[1].val.nontemporal_store(bx, dst);
577 let intr = Intrinsic::find(&name).unwrap_or_else(||
578 bug!("unknown intrinsic '{}'", name));
580 fn one<T>(x: Vec<T>) -> T {
581 assert_eq!(x.len(), 1);
582 x.into_iter().next().unwrap()
584 fn ty_to_type(cx: &CodegenCx<'ll, '_>, t: &intrinsics::Type) -> Vec<&'ll Type> {
585 use intrinsics::Type::*;
587 Void => vec![cx.type_void()],
588 Integer(_signed, _width, llvm_width) => {
589 vec![cx.type_ix( llvm_width as u64)]
593 32 => vec![cx.type_f32()],
594 64 => vec![cx.type_f64()],
598 Pointer(ref t, ref llvm_elem, _const) => {
599 let t = llvm_elem.as_ref().unwrap_or(t);
600 let elem = one(ty_to_type(cx, t));
601 vec![cx.type_ptr_to(elem)]
603 Vector(ref t, ref llvm_elem, length) => {
604 let t = llvm_elem.as_ref().unwrap_or(t);
605 let elem = one(ty_to_type(cx, t));
606 vec![cx.type_vector(elem, length as u64)]
608 Aggregate(false, ref contents) => {
609 let elems = contents.iter()
610 .map(|t| one(ty_to_type(cx, t)))
611 .collect::<Vec<_>>();
612 vec![cx.type_struct( &elems, false)]
614 Aggregate(true, ref contents) => {
616 .flat_map(|t| ty_to_type(cx, t))
622 // This allows an argument list like `foo, (bar, baz),
623 // qux` to be converted into `foo, bar, baz, qux`, integer
624 // arguments to be truncated as needed and pointers to be
627 bx: &Builder<'a, 'll, 'tcx>,
628 t: &intrinsics::Type,
629 arg: &OperandRef<'tcx, &'ll Value>,
630 ) -> Vec<&'ll Value> {
632 intrinsics::Type::Aggregate(true, ref contents) => {
633 // We found a tuple that needs squishing! So
634 // run over the tuple and load each field.
636 // This assumes the type is "simple", i.e. no
637 // destructors, and the contents are SIMD
639 assert!(!bx.cx().type_needs_drop(arg.layout.ty));
640 let (ptr, align) = match arg.val {
641 OperandValue::Ref(ptr, None, align) => (ptr, align),
644 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
645 (0..contents.len()).map(|i| {
646 arg.project_field(bx, i).load(bx).immediate()
649 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
650 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
651 vec![bx.pointercast(arg.immediate(), bx.cx().type_ptr_to(llvm_elem))]
653 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
654 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
656 bx.bitcast(arg.immediate(),
657 bx.cx().type_vector(llvm_elem, length as u64))
660 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
661 // the LLVM intrinsic uses a smaller integer
662 // size than the C intrinsic's signature, so
663 // we have to trim it down here.
664 vec![bx.trunc(arg.immediate(), bx.cx().type_ix(llvm_width as u64))]
666 _ => vec![arg.immediate()],
671 let inputs = intr.inputs.iter()
672 .flat_map(|t| ty_to_type(cx, t))
673 .collect::<Vec<_>>();
675 let outputs = one(ty_to_type(cx, &intr.output));
677 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
678 modify_as_needed(bx, t, arg)
680 assert_eq!(inputs.len(), llargs.len());
682 let val = match intr.definition {
683 intrinsics::IntrinsicDef::Named(name) => {
684 let f = declare::declare_cfn(cx,
686 cx.type_func(&inputs, outputs));
687 bx.call(f, &llargs, None)
692 intrinsics::Type::Aggregate(flatten, ref elems) => {
693 // the output is a tuple so we need to munge it properly
696 for i in 0..elems.len() {
697 let dest = result.project_field(bx, i);
698 let val = bx.extract_value(val, i as u64);
699 bx.store(val, dest.llval, dest.align);
708 if !fn_ty.ret.is_ignore() {
709 if let PassMode::Cast(ty) = fn_ty.ret.mode {
710 let ptr = bx.pointercast(result.llval, cx.type_ptr_to(ty.llvm_type(cx)));
711 bx.store(llval, ptr, result.align);
713 OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout)
714 .val.store(bx, result);
720 bx: &Builder<'a, 'll, 'tcx>,
729 let (size, align) = cx.size_and_align_of(ty);
730 let size = cx.const_usize(size.bytes());
731 let align = align.abi();
732 let dst_ptr = bx.pointercast(dst, cx.type_i8p());
733 let src_ptr = bx.pointercast(src, cx.type_i8p());
735 bx.memmove(dst_ptr, align, src_ptr, align, bx.mul(size, count), volatile)
737 bx.memcpy(dst_ptr, align, src_ptr, align, bx.mul(size, count), volatile)
742 bx: &Builder<'a, 'll, 'tcx>,
750 let (size, align) = cx.size_and_align_of(ty);
751 let size = cx.const_usize(size.bytes());
752 let align = cx.const_i32(align.abi() as i32);
753 let dst = bx.pointercast(dst, cx.type_i8p());
754 call_memset(bx, dst, val, bx.mul(size, count), align, volatile)
758 bx: &Builder<'a, 'll, 'tcx>,
759 cx: &CodegenCx<'ll, 'tcx>,
762 local_ptr: &'ll Value,
765 if bx.sess().no_landing_pads() {
766 bx.call(func, &[data], None);
767 let ptr_align = bx.tcx().data_layout.pointer_align;
768 bx.store(cx.const_null(cx.type_i8p()), dest, ptr_align);
769 } else if wants_msvc_seh(bx.sess()) {
770 codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
772 codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
776 // MSVC's definition of the `rust_try` function.
778 // This implementation uses the new exception handling instructions in LLVM
779 // which have support in LLVM for SEH on MSVC targets. Although these
780 // instructions are meant to work for all targets, as of the time of this
781 // writing, however, LLVM does not recommend the usage of these new instructions
782 // as the old ones are still more optimized.
784 bx: &Builder<'a, 'll, 'tcx>,
785 cx: &CodegenCx<'ll, 'tcx>,
788 local_ptr: &'ll Value,
791 let llfn = get_rust_try_fn(cx, &mut |bx| {
794 bx.set_personality_fn(bx.cx().eh_personality());
796 let normal = bx.build_sibling_block("normal");
797 let catchswitch = bx.build_sibling_block("catchswitch");
798 let catchpad = bx.build_sibling_block("catchpad");
799 let caught = bx.build_sibling_block("caught");
801 let func = llvm::get_param(bx.llfn(), 0);
802 let data = llvm::get_param(bx.llfn(), 1);
803 let local_ptr = llvm::get_param(bx.llfn(), 2);
805 // We're generating an IR snippet that looks like:
807 // declare i32 @rust_try(%func, %data, %ptr) {
808 // %slot = alloca i64*
809 // invoke %func(%data) to label %normal unwind label %catchswitch
815 // %cs = catchswitch within none [%catchpad] unwind to caller
818 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
819 // %ptr[0] = %slot[0]
820 // %ptr[1] = %slot[1]
821 // catchret from %tok to label %caught
827 // This structure follows the basic usage of throw/try/catch in LLVM.
828 // For example, compile this C++ snippet to see what LLVM generates:
830 // #include <stdint.h>
832 // int bar(void (*foo)(void), uint64_t *ret) {
836 // } catch(uint64_t a[2]) {
843 // More information can be found in libstd's seh.rs implementation.
844 let i64p = cx.type_ptr_to(cx.type_i64());
845 let ptr_align = bx.tcx().data_layout.pointer_align;
846 let slot = bx.alloca(i64p, "slot", ptr_align);
847 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
849 normal.ret(cx.const_i32(0));
851 let cs = catchswitch.catch_switch(None, None, 1);
852 catchswitch.add_handler(cs, catchpad.llbb());
855 let tydesc = match tcx.lang_items().msvc_try_filter() {
856 Some(did) => ::consts::get_static(cx, did),
857 None => bug!("msvc_try_filter not defined"),
859 let tok = catchpad.catch_pad(cs, &[tydesc, cx.const_i32(0), slot]);
860 let addr = catchpad.load(slot, ptr_align);
862 let i64_align = bx.tcx().data_layout.i64_align;
863 let arg1 = catchpad.load(addr, i64_align);
864 let val1 = cx.const_i32(1);
865 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
866 let local_ptr = catchpad.bitcast(local_ptr, i64p);
867 catchpad.store(arg1, local_ptr, i64_align);
868 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
869 catchpad.catch_ret(tok, caught.llbb());
871 caught.ret(cx.const_i32(1));
874 // Note that no invoke is used here because by definition this function
875 // can't panic (that's what it's catching).
876 let ret = bx.call(llfn, &[func, data, local_ptr], None);
877 let i32_align = bx.tcx().data_layout.i32_align;
878 bx.store(ret, dest, i32_align);
881 // Definition of the standard "try" function for Rust using the GNU-like model
882 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
885 // This codegen is a little surprising because we always call a shim
886 // function instead of inlining the call to `invoke` manually here. This is done
887 // because in LLVM we're only allowed to have one personality per function
888 // definition. The call to the `try` intrinsic is being inlined into the
889 // function calling it, and that function may already have other personality
890 // functions in play. By calling a shim we're guaranteed that our shim will have
891 // the right personality function.
893 bx: &Builder<'a, 'll, 'tcx>,
894 cx: &CodegenCx<'ll, 'tcx>,
897 local_ptr: &'ll Value,
900 let llfn = get_rust_try_fn(cx, &mut |bx| {
903 // Codegens the shims described above:
906 // invoke %func(%args...) normal %normal unwind %catch
912 // (ptr, _) = landingpad
913 // store ptr, %local_ptr
916 // Note that the `local_ptr` data passed into the `try` intrinsic is
917 // expected to be `*mut *mut u8` for this to actually work, but that's
918 // managed by the standard library.
920 let then = bx.build_sibling_block("then");
921 let catch = bx.build_sibling_block("catch");
923 let func = llvm::get_param(bx.llfn(), 0);
924 let data = llvm::get_param(bx.llfn(), 1);
925 let local_ptr = llvm::get_param(bx.llfn(), 2);
926 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
927 then.ret(cx.const_i32(0));
929 // Type indicator for the exception being thrown.
931 // The first value in this tuple is a pointer to the exception object
932 // being thrown. The second value is a "selector" indicating which of
933 // the landing pad clauses the exception's type had been matched to.
934 // rust_try ignores the selector.
935 let lpad_ty = cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false);
936 let vals = catch.landing_pad(lpad_ty, bx.cx().eh_personality(), 1);
937 catch.add_clause(vals, bx.cx().const_null(cx.type_i8p()));
938 let ptr = catch.extract_value(vals, 0);
939 let ptr_align = bx.tcx().data_layout.pointer_align;
940 catch.store(ptr, catch.bitcast(local_ptr, cx.type_ptr_to(cx.type_i8p())), ptr_align);
941 catch.ret(cx.const_i32(1));
944 // Note that no invoke is used here because by definition this function
945 // can't panic (that's what it's catching).
946 let ret = bx.call(llfn, &[func, data, local_ptr], None);
947 let i32_align = bx.tcx().data_layout.i32_align;
948 bx.store(ret, dest, i32_align);
951 // Helper function to give a Block to a closure to codegen a shim function.
952 // This is currently primarily used for the `try` intrinsic functions above.
953 fn gen_fn<'ll, 'tcx>(
954 cx: &CodegenCx<'ll, 'tcx>,
956 inputs: Vec<Ty<'tcx>>,
958 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
960 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
964 hir::Unsafety::Unsafe,
967 let llfn = declare::define_internal_fn(cx, name, rust_fn_sig);
968 attributes::from_fn_attrs(cx, llfn, None);
969 let bx = Builder::new_block(cx, llfn, "entry-block");
974 // Helper function used to get a handle to the `__rust_try` function used to
977 // This function is only generated once and is then cached.
978 fn get_rust_try_fn<'ll, 'tcx>(
979 cx: &CodegenCx<'ll, 'tcx>,
980 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
982 if let Some(llfn) = cx.rust_try_fn.get() {
986 // Define the type up front for the signature of the rust_try function.
988 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
989 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
993 hir::Unsafety::Unsafe,
996 let output = tcx.types.i32;
997 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
998 cx.rust_try_fn.set(Some(rust_try));
1002 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1003 span_err!(a, b, E0511, "{}", c);
1006 fn generic_simd_intrinsic(
1007 bx: &Builder<'a, 'll, 'tcx>,
1009 callee_ty: Ty<'tcx>,
1010 args: &[OperandRef<'tcx, &'ll Value>],
1012 llret_ty: &'ll Type,
1014 ) -> Result<&'ll Value, ()> {
1015 // macros for error handling:
1016 macro_rules! emit_error {
1020 ($msg: tt, $($fmt: tt)*) => {
1021 span_invalid_monomorphization_error(
1023 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1028 macro_rules! return_error {
1031 emit_error!($($fmt)*);
1037 macro_rules! require {
1038 ($cond: expr, $($fmt: tt)*) => {
1040 return_error!($($fmt)*);
1045 macro_rules! require_simd {
1046 ($ty: expr, $position: expr) => {
1047 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1052 let sig = tcx.normalize_erasing_late_bound_regions(
1053 ty::ParamEnv::reveal_all(),
1054 &callee_ty.fn_sig(tcx),
1056 let arg_tys = sig.inputs();
1058 // every intrinsic takes a SIMD vector as its first argument
1059 require_simd!(arg_tys[0], "input");
1060 let in_ty = arg_tys[0];
1061 let in_elem = arg_tys[0].simd_type(tcx);
1062 let in_len = arg_tys[0].simd_size(tcx);
1064 let comparison = match name {
1065 "simd_eq" => Some(hir::BinOpKind::Eq),
1066 "simd_ne" => Some(hir::BinOpKind::Ne),
1067 "simd_lt" => Some(hir::BinOpKind::Lt),
1068 "simd_le" => Some(hir::BinOpKind::Le),
1069 "simd_gt" => Some(hir::BinOpKind::Gt),
1070 "simd_ge" => Some(hir::BinOpKind::Ge),
1074 if let Some(cmp_op) = comparison {
1075 require_simd!(ret_ty, "return");
1077 let out_len = ret_ty.simd_size(tcx);
1078 require!(in_len == out_len,
1079 "expected return type with length {} (same as input type `{}`), \
1080 found `{}` with length {}",
1083 require!(bx.cx().type_kind(bx.cx().element_type(llret_ty)) == TypeKind::Integer,
1084 "expected return type with integer elements, found `{}` with non-integer `{}`",
1086 ret_ty.simd_type(tcx));
1088 return Ok(compare_simd_types(bx,
1089 args[0].immediate(),
1090 args[1].immediate(),
1096 if name.starts_with("simd_shuffle") {
1097 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1098 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1100 require_simd!(ret_ty, "return");
1102 let out_len = ret_ty.simd_size(tcx);
1103 require!(out_len == n,
1104 "expected return type of length {}, found `{}` with length {}",
1105 n, ret_ty, out_len);
1106 require!(in_elem == ret_ty.simd_type(tcx),
1107 "expected return element type `{}` (element of input `{}`), \
1108 found `{}` with element type `{}`",
1110 ret_ty, ret_ty.simd_type(tcx));
1112 let total_len = in_len as u128 * 2;
1114 let vector = args[2].immediate();
1116 let indices: Option<Vec<_>> = (0..n)
1119 let val = bx.cx().const_get_elt(vector, i as u64);
1120 match bx.cx().const_to_opt_u128(val, true) {
1122 emit_error!("shuffle index #{} is not a constant", arg_idx);
1125 Some(idx) if idx >= total_len => {
1126 emit_error!("shuffle index #{} is out of bounds (limit {})",
1127 arg_idx, total_len);
1130 Some(idx) => Some(bx.cx().const_i32(idx as i32)),
1134 let indices = match indices {
1136 None => return Ok(bx.cx().const_null(llret_ty))
1139 return Ok(bx.shuffle_vector(args[0].immediate(),
1140 args[1].immediate(),
1141 bx.cx().const_vector(&indices)))
1144 if name == "simd_insert" {
1145 require!(in_elem == arg_tys[2],
1146 "expected inserted type `{}` (element of input `{}`), found `{}`",
1147 in_elem, in_ty, arg_tys[2]);
1148 return Ok(bx.insert_element(args[0].immediate(),
1149 args[2].immediate(),
1150 args[1].immediate()))
1152 if name == "simd_extract" {
1153 require!(ret_ty == in_elem,
1154 "expected return type `{}` (element of input `{}`), found `{}`",
1155 in_elem, in_ty, ret_ty);
1156 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1159 if name == "simd_select" {
1160 let m_elem_ty = in_elem;
1162 let v_len = arg_tys[1].simd_size(tcx);
1163 require!(m_len == v_len,
1164 "mismatched lengths: mask length `{}` != other vector length `{}`",
1167 match m_elem_ty.sty {
1169 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1171 // truncate the mask to a vector of i1s
1172 let i1 = bx.cx().type_i1();
1173 let i1xn = bx.cx().type_vector(i1, m_len as u64);
1174 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1175 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1178 fn simd_simple_float_intrinsic(
1180 in_elem: &::rustc::ty::TyS,
1181 in_ty: &::rustc::ty::TyS,
1183 bx: &Builder<'a, 'll, 'tcx>,
1185 args: &[OperandRef<'tcx, &'ll Value>],
1186 ) -> Result<&'ll Value, ()> {
1187 macro_rules! emit_error {
1191 ($msg: tt, $($fmt: tt)*) => {
1192 span_invalid_monomorphization_error(
1194 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1198 macro_rules! return_error {
1201 emit_error!($($fmt)*);
1206 let ety = match in_elem.sty {
1207 ty::Float(f) if f.bit_width() == 32 => {
1208 if in_len < 2 || in_len > 16 {
1210 "unsupported floating-point vector `{}` with length `{}` \
1211 out-of-range [2, 16]",
1216 ty::Float(f) if f.bit_width() == 64 => {
1217 if in_len < 2 || in_len > 8 {
1218 return_error!("unsupported floating-point vector `{}` with length `{}` \
1219 out-of-range [2, 8]",
1225 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1229 return_error!("`{}` is not a floating-point type", in_ty);
1233 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1234 let intrinsic = bx.cx().get_intrinsic(&llvm_name);
1235 let c = bx.call(intrinsic,
1236 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1238 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1244 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1247 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1250 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1253 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1256 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1259 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1262 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1265 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1268 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1271 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1274 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1277 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1280 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1283 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1285 _ => { /* fallthrough */ }
1289 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1290 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1291 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1292 let p0s: String = "p0".repeat(no_pointers);
1294 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1295 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1296 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1297 _ => unreachable!(),
1301 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1302 mut no_pointers: usize) -> &'ll Type {
1303 // FIXME: use cx.layout_of(ty).llvm_type() ?
1304 let mut elem_ty = match elem_ty.sty {
1305 ty::Int(v) => cx.type_int_from_ty( v),
1306 ty::Uint(v) => cx.type_uint_from_ty( v),
1307 ty::Float(v) => cx.type_float_from_ty( v),
1308 _ => unreachable!(),
1310 while no_pointers > 0 {
1311 elem_ty = cx.type_ptr_to(elem_ty);
1314 cx.type_vector(elem_ty, vec_len as u64)
1318 if name == "simd_gather" {
1319 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1320 // mask: <N x i{M}>) -> <N x T>
1321 // * N: number of elements in the input vectors
1322 // * T: type of the element to load
1323 // * M: any integer width is supported, will be truncated to i1
1325 // All types must be simd vector types
1326 require_simd!(in_ty, "first");
1327 require_simd!(arg_tys[1], "second");
1328 require_simd!(arg_tys[2], "third");
1329 require_simd!(ret_ty, "return");
1331 // Of the same length:
1332 require!(in_len == arg_tys[1].simd_size(tcx),
1333 "expected {} argument with length {} (same as input type `{}`), \
1334 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1335 arg_tys[1].simd_size(tcx));
1336 require!(in_len == arg_tys[2].simd_size(tcx),
1337 "expected {} argument with length {} (same as input type `{}`), \
1338 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1339 arg_tys[2].simd_size(tcx));
1341 // The return type must match the first argument type
1342 require!(ret_ty == in_ty,
1343 "expected return type `{}`, found `{}`",
1346 // This counts how many pointers
1347 fn ptr_count(t: ty::Ty) -> usize {
1349 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1355 fn non_ptr(t: ty::Ty) -> ty::Ty {
1357 ty::RawPtr(p) => non_ptr(p.ty),
1362 // The second argument must be a simd vector with an element type that's a pointer
1363 // to the element type of the first argument
1364 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1365 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1366 non_ptr(arg_tys[1].simd_type(tcx))),
1368 require!(false, "expected element type `{}` of second argument `{}` \
1369 to be a pointer to the element type `{}` of the first \
1370 argument `{}`, found `{}` != `*_ {}`",
1371 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1372 arg_tys[1].simd_type(tcx).sty, in_elem);
1376 assert!(pointer_count > 0);
1377 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1378 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1380 // The element type of the third argument must be a signed integer type of any width:
1381 match arg_tys[2].simd_type(tcx).sty {
1384 require!(false, "expected element type `{}` of third argument `{}` \
1385 to be a signed integer type",
1386 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1390 // Alignment of T, must be a constant integer value:
1391 let alignment_ty = bx.cx().type_i32();
1392 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1394 // Truncate the mask vector to a vector of i1s:
1395 let (mask, mask_ty) = {
1396 let i1 = bx.cx().type_i1();
1397 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1398 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1401 // Type of the vector of pointers:
1402 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1403 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1405 // Type of the vector of elements:
1406 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1407 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1409 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1410 llvm_elem_vec_str, llvm_pointer_vec_str);
1411 let f = declare::declare_cfn(bx.cx(), &llvm_intrinsic,
1412 bx.cx().type_func(&[
1413 llvm_pointer_vec_ty,
1416 llvm_elem_vec_ty], llvm_elem_vec_ty));
1417 llvm::SetUnnamedAddr(f, false);
1418 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1423 if name == "simd_scatter" {
1424 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1425 // mask: <N x i{M}>) -> ()
1426 // * N: number of elements in the input vectors
1427 // * T: type of the element to load
1428 // * M: any integer width is supported, will be truncated to i1
1430 // All types must be simd vector types
1431 require_simd!(in_ty, "first");
1432 require_simd!(arg_tys[1], "second");
1433 require_simd!(arg_tys[2], "third");
1435 // Of the same length:
1436 require!(in_len == arg_tys[1].simd_size(tcx),
1437 "expected {} argument with length {} (same as input type `{}`), \
1438 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1439 arg_tys[1].simd_size(tcx));
1440 require!(in_len == arg_tys[2].simd_size(tcx),
1441 "expected {} argument with length {} (same as input type `{}`), \
1442 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1443 arg_tys[2].simd_size(tcx));
1445 // This counts how many pointers
1446 fn ptr_count(t: ty::Ty) -> usize {
1448 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1454 fn non_ptr(t: ty::Ty) -> ty::Ty {
1456 ty::RawPtr(p) => non_ptr(p.ty),
1461 // The second argument must be a simd vector with an element type that's a pointer
1462 // to the element type of the first argument
1463 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1464 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1465 => (ptr_count(arg_tys[1].simd_type(tcx)),
1466 non_ptr(arg_tys[1].simd_type(tcx))),
1468 require!(false, "expected element type `{}` of second argument `{}` \
1469 to be a pointer to the element type `{}` of the first \
1470 argument `{}`, found `{}` != `*mut {}`",
1471 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1472 arg_tys[1].simd_type(tcx).sty, in_elem);
1476 assert!(pointer_count > 0);
1477 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1478 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1480 // The element type of the third argument must be a signed integer type of any width:
1481 match arg_tys[2].simd_type(tcx).sty {
1484 require!(false, "expected element type `{}` of third argument `{}` \
1485 to be a signed integer type",
1486 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1490 // Alignment of T, must be a constant integer value:
1491 let alignment_ty = bx.cx().type_i32();
1492 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1494 // Truncate the mask vector to a vector of i1s:
1495 let (mask, mask_ty) = {
1496 let i1 = bx.cx().type_i1();
1497 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1498 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1501 let ret_t = bx.cx().type_void();
1503 // Type of the vector of pointers:
1504 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1505 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1507 // Type of the vector of elements:
1508 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1509 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1511 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1512 llvm_elem_vec_str, llvm_pointer_vec_str);
1513 let f = declare::declare_cfn(bx.cx(), &llvm_intrinsic,
1514 bx.cx().type_func(&[llvm_elem_vec_ty,
1515 llvm_pointer_vec_ty,
1518 llvm::SetUnnamedAddr(f, false);
1519 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1524 macro_rules! arith_red {
1525 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1527 require!(ret_ty == in_elem,
1528 "expected return type `{}` (element of input `{}`), found `{}`",
1529 in_elem, in_ty, ret_ty);
1530 return match in_elem.sty {
1531 ty::Int(_) | ty::Uint(_) => {
1532 let r = bx.$integer_reduce(args[0].immediate());
1534 // if overflow occurs, the result is the
1535 // mathematical result modulo 2^n:
1536 if name.contains("mul") {
1537 Ok(bx.mul(args[1].immediate(), r))
1539 Ok(bx.add(args[1].immediate(), r))
1542 Ok(bx.$integer_reduce(args[0].immediate()))
1546 // ordered arithmetic reductions take an accumulator
1547 let acc = if $ordered {
1548 let acc = args[1].immediate();
1549 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1550 // * if the accumulator of the fadd isn't 0, incorrect
1551 // code is generated
1552 // * if the accumulator of the fmul isn't 1, incorrect
1553 // code is generated
1554 match bx.cx().const_get_real(acc) {
1555 None => return_error!("accumulator of {} is not a constant", $name),
1556 Some((v, loses_info)) => {
1557 if $name.contains("mul") && v != 1.0_f64 {
1558 return_error!("accumulator of {} is not 1.0", $name);
1559 } else if $name.contains("add") && v != 0.0_f64 {
1560 return_error!("accumulator of {} is not 0.0", $name);
1561 } else if loses_info {
1562 return_error!("accumulator of {} loses information", $name);
1568 // unordered arithmetic reductions do not:
1569 match f.bit_width() {
1570 32 => bx.cx().const_undef(bx.cx().type_f32()),
1571 64 => bx.cx().const_undef(bx.cx().type_f64()),
1574 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1575 $name, in_ty, in_elem, v, ret_ty
1580 Ok(bx.$float_reduce(acc, args[0].immediate()))
1584 "unsupported {} from `{}` with element `{}` to `{}`",
1585 $name, in_ty, in_elem, ret_ty
1593 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1594 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1595 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1596 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1598 macro_rules! minmax_red {
1599 ($name:tt: $int_red:ident, $float_red:ident) => {
1601 require!(ret_ty == in_elem,
1602 "expected return type `{}` (element of input `{}`), found `{}`",
1603 in_elem, in_ty, ret_ty);
1604 return match in_elem.sty {
1606 Ok(bx.$int_red(args[0].immediate(), true))
1609 Ok(bx.$int_red(args[0].immediate(), false))
1612 Ok(bx.$float_red(args[0].immediate()))
1615 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1616 $name, in_ty, in_elem, ret_ty)
1624 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1625 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1627 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1628 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1630 macro_rules! bitwise_red {
1631 ($name:tt : $red:ident, $boolean:expr) => {
1633 let input = if !$boolean {
1634 require!(ret_ty == in_elem,
1635 "expected return type `{}` (element of input `{}`), found `{}`",
1636 in_elem, in_ty, ret_ty);
1640 ty::Int(_) | ty::Uint(_) => {},
1642 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1643 $name, in_ty, in_elem, ret_ty)
1647 // boolean reductions operate on vectors of i1s:
1648 let i1 = bx.cx().type_i1();
1649 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1650 bx.trunc(args[0].immediate(), i1xn)
1652 return match in_elem.sty {
1653 ty::Int(_) | ty::Uint(_) => {
1654 let r = bx.$red(input);
1659 bx.zext(r, bx.cx().type_bool())
1664 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1665 $name, in_ty, in_elem, ret_ty)
1672 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1673 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1674 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1675 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1676 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1678 if name == "simd_cast" {
1679 require_simd!(ret_ty, "return");
1680 let out_len = ret_ty.simd_size(tcx);
1681 require!(in_len == out_len,
1682 "expected return type with length {} (same as input type `{}`), \
1683 found `{}` with length {}",
1686 // casting cares about nominal type, not just structural type
1687 let out_elem = ret_ty.simd_type(tcx);
1689 if in_elem == out_elem { return Ok(args[0].immediate()); }
1691 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1693 let (in_style, in_width) = match in_elem.sty {
1694 // vectors of pointer-sized integers should've been
1695 // disallowed before here, so this unwrap is safe.
1696 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1697 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1698 ty::Float(f) => (Style::Float, f.bit_width()),
1699 _ => (Style::Unsupported, 0)
1701 let (out_style, out_width) = match out_elem.sty {
1702 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1703 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1704 ty::Float(f) => (Style::Float, f.bit_width()),
1705 _ => (Style::Unsupported, 0)
1708 match (in_style, out_style) {
1709 (Style::Int(in_is_signed), Style::Int(_)) => {
1710 return Ok(match in_width.cmp(&out_width) {
1711 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1712 Ordering::Equal => args[0].immediate(),
1713 Ordering::Less => if in_is_signed {
1714 bx.sext(args[0].immediate(), llret_ty)
1716 bx.zext(args[0].immediate(), llret_ty)
1720 (Style::Int(in_is_signed), Style::Float) => {
1721 return Ok(if in_is_signed {
1722 bx.sitofp(args[0].immediate(), llret_ty)
1724 bx.uitofp(args[0].immediate(), llret_ty)
1727 (Style::Float, Style::Int(out_is_signed)) => {
1728 return Ok(if out_is_signed {
1729 bx.fptosi(args[0].immediate(), llret_ty)
1731 bx.fptoui(args[0].immediate(), llret_ty)
1734 (Style::Float, Style::Float) => {
1735 return Ok(match in_width.cmp(&out_width) {
1736 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1737 Ordering::Equal => args[0].immediate(),
1738 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1741 _ => {/* Unsupported. Fallthrough. */}
1744 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1748 macro_rules! arith {
1749 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1750 $(if name == stringify!($name) {
1752 $($(ty::$p(_))|* => {
1753 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1758 "unsupported operation on `{}` with element `{}`",
1765 simd_add: Uint, Int => add, Float => fadd;
1766 simd_sub: Uint, Int => sub, Float => fsub;
1767 simd_mul: Uint, Int => mul, Float => fmul;
1768 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1769 simd_rem: Uint => urem, Int => srem, Float => frem;
1770 simd_shl: Uint, Int => shl;
1771 simd_shr: Uint => lshr, Int => ashr;
1772 simd_and: Uint, Int => and;
1773 simd_or: Uint, Int => or;
1774 simd_xor: Uint, Int => xor;
1775 simd_fmax: Float => maxnum;
1776 simd_fmin: Float => minnum;
1778 span_bug!(span, "unknown SIMD intrinsic");
1781 // Returns the width of an int Ty, and if it's signed or not
1782 // Returns None if the type is not an integer
1783 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1785 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1787 ty::Int(t) => Some((match t {
1788 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1789 ast::IntTy::I8 => 8,
1790 ast::IntTy::I16 => 16,
1791 ast::IntTy::I32 => 32,
1792 ast::IntTy::I64 => 64,
1793 ast::IntTy::I128 => 128,
1795 ty::Uint(t) => Some((match t {
1796 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1797 ast::UintTy::U8 => 8,
1798 ast::UintTy::U16 => 16,
1799 ast::UintTy::U32 => 32,
1800 ast::UintTy::U64 => 64,
1801 ast::UintTy::U128 => 128,
1807 // Returns the width of a float TypeVariant
1808 // Returns None if the type is not a float
1809 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1811 ty::Float(t) => Some(t.bit_width() as u64),