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};
15 use llvm::{self, TypeKind};
17 use abi::{Abi, FnType, LlvmType, PassMode};
18 use mir::place::PlaceRef;
19 use mir::operand::{OperandRef, OperandValue};
25 use type_of::LayoutLlvmExt;
26 use rustc::ty::{self, Ty};
27 use rustc::ty::layout::LayoutOf;
30 use syntax::symbol::Symbol;
34 use traits::BuilderMethods;
36 use rustc::session::Session;
39 use std::cmp::Ordering;
42 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
43 let llvm_name = match name {
44 "sqrtf32" => "llvm.sqrt.f32",
45 "sqrtf64" => "llvm.sqrt.f64",
46 "powif32" => "llvm.powi.f32",
47 "powif64" => "llvm.powi.f64",
48 "sinf32" => "llvm.sin.f32",
49 "sinf64" => "llvm.sin.f64",
50 "cosf32" => "llvm.cos.f32",
51 "cosf64" => "llvm.cos.f64",
52 "powf32" => "llvm.pow.f32",
53 "powf64" => "llvm.pow.f64",
54 "expf32" => "llvm.exp.f32",
55 "expf64" => "llvm.exp.f64",
56 "exp2f32" => "llvm.exp2.f32",
57 "exp2f64" => "llvm.exp2.f64",
58 "logf32" => "llvm.log.f32",
59 "logf64" => "llvm.log.f64",
60 "log10f32" => "llvm.log10.f32",
61 "log10f64" => "llvm.log10.f64",
62 "log2f32" => "llvm.log2.f32",
63 "log2f64" => "llvm.log2.f64",
64 "fmaf32" => "llvm.fma.f32",
65 "fmaf64" => "llvm.fma.f64",
66 "fabsf32" => "llvm.fabs.f32",
67 "fabsf64" => "llvm.fabs.f64",
68 "copysignf32" => "llvm.copysign.f32",
69 "copysignf64" => "llvm.copysign.f64",
70 "floorf32" => "llvm.floor.f32",
71 "floorf64" => "llvm.floor.f64",
72 "ceilf32" => "llvm.ceil.f32",
73 "ceilf64" => "llvm.ceil.f64",
74 "truncf32" => "llvm.trunc.f32",
75 "truncf64" => "llvm.trunc.f64",
76 "rintf32" => "llvm.rint.f32",
77 "rintf64" => "llvm.rint.f64",
78 "nearbyintf32" => "llvm.nearbyint.f32",
79 "nearbyintf64" => "llvm.nearbyint.f64",
80 "roundf32" => "llvm.round.f32",
81 "roundf64" => "llvm.round.f64",
82 "assume" => "llvm.assume",
83 "abort" => "llvm.trap",
86 Some(cx.get_intrinsic(&llvm_name))
89 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
90 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
91 /// add them to librustc_codegen_llvm/context.rs
92 pub fn codegen_intrinsic_call(
93 bx: &Builder<'a, 'll, 'tcx>,
95 fn_ty: &FnType<'tcx, Ty<'tcx>>,
96 args: &[OperandRef<'tcx, &'ll Value>],
103 let (def_id, substs) = match callee_ty.sty {
104 ty::FnDef(def_id, substs) => (def_id, substs),
105 _ => bug!("expected fn item type, found {}", callee_ty)
108 let sig = callee_ty.fn_sig(tcx);
109 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
110 let arg_tys = sig.inputs();
111 let ret_ty = sig.output();
112 let name = &*tcx.item_name(def_id).as_str();
114 let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
115 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
117 let simple = get_simple_intrinsic(cx, name);
118 let llval = match name {
119 _ if simple.is_some() => {
120 bx.call(simple.unwrap(),
121 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
128 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
129 bx.call(expect, &[args[0].immediate(), C_bool(cx, true)], None)
132 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
133 bx.call(expect, &[args[0].immediate(), C_bool(cx, false)], None)
136 try_intrinsic(bx, cx,
144 let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
145 bx.call(llfn, &[], None)
148 let tp_ty = substs.type_at(0);
149 C_usize(cx, cx.size_of(tp_ty).bytes())
152 let tp_ty = substs.type_at(0);
153 if let OperandValue::Pair(_, meta) = args[0].val {
155 glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
158 C_usize(cx, cx.size_of(tp_ty).bytes())
162 let tp_ty = substs.type_at(0);
163 C_usize(cx, cx.align_of(tp_ty).abi())
165 "min_align_of_val" => {
166 let tp_ty = substs.type_at(0);
167 if let OperandValue::Pair(_, meta) = args[0].val {
169 glue::size_and_align_of_dst(bx, tp_ty, Some(meta));
172 C_usize(cx, cx.align_of(tp_ty).abi())
176 let tp_ty = substs.type_at(0);
177 C_usize(cx, cx.align_of(tp_ty).pref())
180 let tp_ty = substs.type_at(0);
181 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
182 C_str_slice(cx, ty_name)
185 C_u64(cx, cx.tcx.type_id_hash(substs.type_at(0)))
188 let ty = substs.type_at(0);
189 if !cx.layout_of(ty).is_zst() {
190 // Just zero out the stack slot.
191 // If we store a zero constant, LLVM will drown in vreg allocation for large data
192 // structures, and the generated code will be awful. (A telltale sign of this is
193 // large quantities of `mov [byte ptr foo],0` in the generated code.)
194 memset_intrinsic(bx, false, ty, llresult, C_u8(cx, 0), C_usize(cx, 1));
198 // Effectively no-ops
199 "uninit" | "forget" => {
203 let tp_ty = substs.type_at(0);
205 C_bool(cx, bx.cx.type_needs_drop(tp_ty))
208 let ptr = args[0].immediate();
209 let offset = args[1].immediate();
210 bx.inbounds_gep(ptr, &[offset])
213 let ptr = args[0].immediate();
214 let offset = args[1].immediate();
215 bx.gep(ptr, &[offset])
218 "copy_nonoverlapping" => {
219 copy_intrinsic(bx, false, false, substs.type_at(0),
220 args[1].immediate(), args[0].immediate(), args[2].immediate())
223 copy_intrinsic(bx, true, false, substs.type_at(0),
224 args[1].immediate(), args[0].immediate(), args[2].immediate())
227 memset_intrinsic(bx, false, substs.type_at(0),
228 args[0].immediate(), args[1].immediate(), args[2].immediate())
231 "volatile_copy_nonoverlapping_memory" => {
232 copy_intrinsic(bx, false, true, substs.type_at(0),
233 args[0].immediate(), args[1].immediate(), args[2].immediate())
235 "volatile_copy_memory" => {
236 copy_intrinsic(bx, true, true, substs.type_at(0),
237 args[0].immediate(), args[1].immediate(), args[2].immediate())
239 "volatile_set_memory" => {
240 memset_intrinsic(bx, true, substs.type_at(0),
241 args[0].immediate(), args[1].immediate(), args[2].immediate())
243 "volatile_load" | "unaligned_volatile_load" => {
244 let tp_ty = substs.type_at(0);
245 let mut ptr = args[0].immediate();
246 if let PassMode::Cast(ty) = fn_ty.ret.mode {
247 ptr = bx.pointercast(ptr, ty.llvm_type(cx).ptr_to());
249 let load = bx.volatile_load(ptr);
250 let align = if name == "unaligned_volatile_load" {
253 cx.align_of(tp_ty).abi() as u32
256 llvm::LLVMSetAlignment(load, align);
258 to_immediate(bx, load, cx.layout_of(tp_ty))
260 "volatile_store" => {
261 let dst = args[0].deref(bx.cx);
262 args[1].val.volatile_store(bx, dst);
265 "unaligned_volatile_store" => {
266 let dst = args[0].deref(bx.cx);
267 args[1].val.unaligned_volatile_store(bx, dst);
270 "prefetch_read_data" | "prefetch_write_data" |
271 "prefetch_read_instruction" | "prefetch_write_instruction" => {
272 let expect = cx.get_intrinsic(&("llvm.prefetch"));
273 let (rw, cache_type) = match name {
274 "prefetch_read_data" => (0, 1),
275 "prefetch_write_data" => (1, 1),
276 "prefetch_read_instruction" => (0, 0),
277 "prefetch_write_instruction" => (1, 0),
284 C_i32(cx, cache_type)
287 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
288 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
289 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
290 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
291 "rotate_left" | "rotate_right" => {
293 match int_type_width_signed(ty, cx) {
294 Some((width, signed)) =>
297 let y = C_bool(bx.cx, false);
298 let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
299 bx.call(llfn, &[args[0].immediate(), y], None)
301 "ctlz_nonzero" | "cttz_nonzero" => {
302 let y = C_bool(bx.cx, true);
303 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
304 let llfn = cx.get_intrinsic(llvm_name);
305 bx.call(llfn, &[args[0].immediate(), y], None)
307 "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
308 &[args[0].immediate()], None),
311 args[0].immediate() // byte swap a u8/i8 is just a no-op
313 bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
314 &[args[0].immediate()], None)
318 bx.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
319 &[args[0].immediate()], None)
321 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
322 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
323 if signed { 's' } else { 'u' },
325 let llfn = bx.cx.get_intrinsic(&intrinsic);
327 // Convert `i1` to a `bool`, and write it to the out parameter
328 let pair = bx.call(llfn, &[
332 let val = bx.extract_value(pair, 0);
333 let overflow = bx.zext(bx.extract_value(pair, 1), Type::bool(cx));
335 let dest = result.project_field(bx, 0);
336 bx.store(val, dest.llval, dest.align);
337 let dest = result.project_field(bx, 1);
338 bx.store(overflow, dest.llval, dest.align);
342 "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()),
343 "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()),
344 "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()),
347 bx.exactsdiv(args[0].immediate(), args[1].immediate())
349 bx.exactudiv(args[0].immediate(), args[1].immediate())
353 bx.sdiv(args[0].immediate(), args[1].immediate())
355 bx.udiv(args[0].immediate(), args[1].immediate())
359 bx.srem(args[0].immediate(), args[1].immediate())
361 bx.urem(args[0].immediate(), args[1].immediate())
363 "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()),
366 bx.ashr(args[0].immediate(), args[1].immediate())
368 bx.lshr(args[0].immediate(), args[1].immediate())
370 "rotate_left" | "rotate_right" => {
371 let is_left = name == "rotate_left";
372 let val = args[0].immediate();
373 let raw_shift = args[1].immediate();
374 if llvm_util::get_major_version() >= 7 {
375 // rotate = funnel shift with first two args the same
376 let llvm_name = &format!("llvm.fsh{}.i{}",
377 if is_left { 'l' } else { 'r' }, width);
378 let llfn = cx.get_intrinsic(llvm_name);
379 bx.call(llfn, &[val, val, raw_shift], None)
381 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
382 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
383 let width = C_uint(Type::ix(cx, width), width);
384 let shift = bx.urem(raw_shift, width);
385 let inv_shift = bx.urem(bx.sub(width, raw_shift), width);
386 let shift1 = bx.shl(val, if is_left { shift } else { inv_shift });
387 let shift2 = bx.lshr(val, if !is_left { shift } else { inv_shift });
388 bx.or(shift1, shift2)
394 span_invalid_monomorphization_error(
396 &format!("invalid monomorphization of `{}` intrinsic: \
397 expected basic integer type, found `{}`", name, ty));
402 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
403 let sty = &arg_tys[0].sty;
404 match float_type_width(sty) {
407 "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
408 "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
409 "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
410 "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
411 "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()),
415 span_invalid_monomorphization_error(
417 &format!("invalid monomorphization of `{}` intrinsic: \
418 expected basic float type, found `{}`", name, sty));
425 "discriminant_value" => {
426 args[0].deref(bx.cx).codegen_get_discr(bx, ret_ty)
429 name if name.starts_with("simd_") => {
430 match generic_simd_intrinsic(bx, name,
439 // This requires that atomic intrinsics follow a specific naming pattern:
440 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
441 name if name.starts_with("atomic_") => {
442 use llvm::AtomicOrdering::*;
444 let split: Vec<&str> = name.split('_').collect();
446 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
447 let (order, failorder) = match split.len() {
448 2 => (SequentiallyConsistent, SequentiallyConsistent),
449 3 => match split[2] {
450 "unordered" => (Unordered, Unordered),
451 "relaxed" => (Monotonic, Monotonic),
452 "acq" => (Acquire, Acquire),
453 "rel" => (Release, Monotonic),
454 "acqrel" => (AcquireRelease, Acquire),
455 "failrelaxed" if is_cxchg =>
456 (SequentiallyConsistent, Monotonic),
457 "failacq" if is_cxchg =>
458 (SequentiallyConsistent, Acquire),
459 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
461 4 => match (split[2], split[3]) {
462 ("acq", "failrelaxed") if is_cxchg =>
463 (Acquire, Monotonic),
464 ("acqrel", "failrelaxed") if is_cxchg =>
465 (AcquireRelease, Monotonic),
466 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
468 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
471 let invalid_monomorphization = |ty| {
472 span_invalid_monomorphization_error(tcx.sess, span,
473 &format!("invalid monomorphization of `{}` intrinsic: \
474 expected basic integer type, found `{}`", name, ty));
478 "cxchg" | "cxchgweak" => {
479 let ty = substs.type_at(0);
480 if int_type_width_signed(ty, cx).is_some() {
481 let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False };
482 let pair = bx.atomic_cmpxchg(
489 let val = bx.extract_value(pair, 0);
490 let success = bx.zext(bx.extract_value(pair, 1), Type::bool(bx.cx));
492 let dest = result.project_field(bx, 0);
493 bx.store(val, dest.llval, dest.align);
494 let dest = result.project_field(bx, 1);
495 bx.store(success, dest.llval, dest.align);
498 return invalid_monomorphization(ty);
503 let ty = substs.type_at(0);
504 if int_type_width_signed(ty, cx).is_some() {
505 let size = cx.size_of(ty);
506 bx.atomic_load(args[0].immediate(), order, size)
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_store(args[1].immediate(), args[0].immediate(), order, size);
519 return invalid_monomorphization(ty);
524 bx.atomic_fence(order, llvm::SynchronizationScope::CrossThread);
528 "singlethreadfence" => {
529 bx.atomic_fence(order, llvm::SynchronizationScope::SingleThread);
533 // These are all AtomicRMW ops
535 let atom_op = match op {
536 "xchg" => llvm::AtomicXchg,
537 "xadd" => llvm::AtomicAdd,
538 "xsub" => llvm::AtomicSub,
539 "and" => llvm::AtomicAnd,
540 "nand" => llvm::AtomicNand,
541 "or" => llvm::AtomicOr,
542 "xor" => llvm::AtomicXor,
543 "max" => llvm::AtomicMax,
544 "min" => llvm::AtomicMin,
545 "umax" => llvm::AtomicUMax,
546 "umin" => llvm::AtomicUMin,
547 _ => cx.sess().fatal("unknown atomic operation")
550 let ty = substs.type_at(0);
551 if int_type_width_signed(ty, cx).is_some() {
552 bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order)
554 return invalid_monomorphization(ty);
560 "nontemporal_store" => {
561 let dst = args[0].deref(bx.cx);
562 args[1].val.nontemporal_store(bx, dst);
567 let intr = Intrinsic::find(&name).unwrap_or_else(||
568 bug!("unknown intrinsic '{}'", name));
570 fn one<T>(x: Vec<T>) -> T {
571 assert_eq!(x.len(), 1);
572 x.into_iter().next().unwrap()
574 fn ty_to_type(cx: &CodegenCx<'ll, '_>, t: &intrinsics::Type) -> Vec<&'ll Type> {
575 use intrinsics::Type::*;
577 Void => vec![Type::void(cx)],
578 Integer(_signed, _width, llvm_width) => {
579 vec![Type::ix(cx, llvm_width as u64)]
583 32 => vec![Type::f32(cx)],
584 64 => vec![Type::f64(cx)],
588 Pointer(ref t, ref llvm_elem, _const) => {
589 let t = llvm_elem.as_ref().unwrap_or(t);
590 let elem = one(ty_to_type(cx, t));
593 Vector(ref t, ref llvm_elem, length) => {
594 let t = llvm_elem.as_ref().unwrap_or(t);
595 let elem = one(ty_to_type(cx, t));
596 vec![Type::vector::<Value>(elem, length as u64)]
598 Aggregate(false, ref contents) => {
599 let elems = contents.iter()
600 .map(|t| one(ty_to_type(cx, t)))
601 .collect::<Vec<_>>();
602 vec![Type::struct_(cx, &elems, false)]
604 Aggregate(true, ref contents) => {
606 .flat_map(|t| ty_to_type(cx, t))
612 // This allows an argument list like `foo, (bar, baz),
613 // qux` to be converted into `foo, bar, baz, qux`, integer
614 // arguments to be truncated as needed and pointers to be
617 bx: &Builder<'a, 'll, 'tcx>,
618 t: &intrinsics::Type,
619 arg: &OperandRef<'tcx, &'ll Value>,
620 ) -> Vec<&'ll Value> {
622 intrinsics::Type::Aggregate(true, ref contents) => {
623 // We found a tuple that needs squishing! So
624 // run over the tuple and load each field.
626 // This assumes the type is "simple", i.e. no
627 // destructors, and the contents are SIMD
629 assert!(!bx.cx.type_needs_drop(arg.layout.ty));
630 let (ptr, align) = match arg.val {
631 OperandValue::Ref(ptr, None, align) => (ptr, align),
634 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
635 (0..contents.len()).map(|i| {
636 arg.project_field(bx, i).load(bx).immediate()
639 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
640 let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
641 vec![bx.pointercast(arg.immediate(), llvm_elem.ptr_to())]
643 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
644 let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
646 bx.bitcast(arg.immediate(),
647 Type::vector::<Value>(llvm_elem, length as u64))
650 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
651 // the LLVM intrinsic uses a smaller integer
652 // size than the C intrinsic's signature, so
653 // we have to trim it down here.
654 vec![bx.trunc(arg.immediate(), Type::ix(bx.cx, llvm_width as u64))]
656 _ => vec![arg.immediate()],
661 let inputs = intr.inputs.iter()
662 .flat_map(|t| ty_to_type(cx, t))
663 .collect::<Vec<_>>();
665 let outputs = one(ty_to_type(cx, &intr.output));
667 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
668 modify_as_needed(bx, t, arg)
670 assert_eq!(inputs.len(), llargs.len());
672 let val = match intr.definition {
673 intrinsics::IntrinsicDef::Named(name) => {
674 let f = declare::declare_cfn(cx,
676 Type::func::<Value>(&inputs, outputs));
677 bx.call(f, &llargs, None)
682 intrinsics::Type::Aggregate(flatten, ref elems) => {
683 // the output is a tuple so we need to munge it properly
686 for i in 0..elems.len() {
687 let dest = result.project_field(bx, i);
688 let val = bx.extract_value(val, i as u64);
689 bx.store(val, dest.llval, dest.align);
698 if !fn_ty.ret.is_ignore() {
699 if let PassMode::Cast(ty) = fn_ty.ret.mode {
700 let ptr = bx.pointercast(result.llval, ty.llvm_type(cx).ptr_to());
701 bx.store(llval, ptr, result.align);
703 OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout)
704 .val.store(bx, result);
710 bx: &Builder<'a, 'll, 'tcx>,
719 let (size, align) = cx.size_and_align_of(ty);
720 let size = C_usize(cx, size.bytes());
721 let align = align.abi();
722 let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
723 let src_ptr = bx.pointercast(src, Type::i8p(cx));
725 bx.memmove(dst_ptr, align, src_ptr, align, bx.mul(size, count), volatile)
727 bx.memcpy(dst_ptr, align, src_ptr, align, bx.mul(size, count), volatile)
732 bx: &Builder<'a, 'll, 'tcx>,
740 let (size, align) = cx.size_and_align_of(ty);
741 let size = C_usize(cx, size.bytes());
742 let align = C_i32(cx, align.abi() as i32);
743 let dst = bx.pointercast(dst, Type::i8p(cx));
744 call_memset(bx, dst, val, bx.mul(size, count), align, volatile)
748 bx: &Builder<'a, 'll, 'tcx>,
749 cx: &CodegenCx<'ll, 'tcx>,
752 local_ptr: &'ll Value,
755 if bx.sess().no_landing_pads() {
756 bx.call(func, &[data], None);
757 let ptr_align = bx.tcx().data_layout.pointer_align;
758 bx.store(C_null(Type::i8p(&bx.cx)), dest, ptr_align);
759 } else if wants_msvc_seh(bx.sess()) {
760 codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
762 codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
766 // MSVC's definition of the `rust_try` function.
768 // This implementation uses the new exception handling instructions in LLVM
769 // which have support in LLVM for SEH on MSVC targets. Although these
770 // instructions are meant to work for all targets, as of the time of this
771 // writing, however, LLVM does not recommend the usage of these new instructions
772 // as the old ones are still more optimized.
774 bx: &Builder<'a, 'll, 'tcx>,
775 cx: &CodegenCx<'ll, 'tcx>,
778 local_ptr: &'ll Value,
781 let llfn = get_rust_try_fn(cx, &mut |bx| {
784 bx.set_personality_fn(bx.cx.eh_personality());
786 let normal = bx.build_sibling_block("normal");
787 let catchswitch = bx.build_sibling_block("catchswitch");
788 let catchpad = bx.build_sibling_block("catchpad");
789 let caught = bx.build_sibling_block("caught");
791 let func = llvm::get_param(bx.llfn(), 0);
792 let data = llvm::get_param(bx.llfn(), 1);
793 let local_ptr = llvm::get_param(bx.llfn(), 2);
795 // We're generating an IR snippet that looks like:
797 // declare i32 @rust_try(%func, %data, %ptr) {
798 // %slot = alloca i64*
799 // invoke %func(%data) to label %normal unwind label %catchswitch
805 // %cs = catchswitch within none [%catchpad] unwind to caller
808 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
809 // %ptr[0] = %slot[0]
810 // %ptr[1] = %slot[1]
811 // catchret from %tok to label %caught
817 // This structure follows the basic usage of throw/try/catch in LLVM.
818 // For example, compile this C++ snippet to see what LLVM generates:
820 // #include <stdint.h>
822 // int bar(void (*foo)(void), uint64_t *ret) {
826 // } catch(uint64_t a[2]) {
833 // More information can be found in libstd's seh.rs implementation.
834 let i64p = Type::i64(cx).ptr_to();
835 let ptr_align = bx.tcx().data_layout.pointer_align;
836 let slot = bx.alloca(i64p, "slot", ptr_align);
837 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
839 normal.ret(C_i32(cx, 0));
841 let cs = catchswitch.catch_switch(None, None, 1);
842 catchswitch.add_handler(cs, catchpad.llbb());
845 let tydesc = match tcx.lang_items().msvc_try_filter() {
846 Some(did) => ::consts::get_static(cx, did),
847 None => bug!("msvc_try_filter not defined"),
849 let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(cx, 0), slot]);
850 let addr = catchpad.load(slot, ptr_align);
852 let i64_align = bx.tcx().data_layout.i64_align;
853 let arg1 = catchpad.load(addr, i64_align);
854 let val1 = C_i32(cx, 1);
855 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
856 let local_ptr = catchpad.bitcast(local_ptr, i64p);
857 catchpad.store(arg1, local_ptr, i64_align);
858 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
859 catchpad.catch_ret(tok, caught.llbb());
861 caught.ret(C_i32(cx, 1));
864 // Note that no invoke is used here because by definition this function
865 // can't panic (that's what it's catching).
866 let ret = bx.call(llfn, &[func, data, local_ptr], None);
867 let i32_align = bx.tcx().data_layout.i32_align;
868 bx.store(ret, dest, i32_align);
871 // Definition of the standard "try" function for Rust using the GNU-like model
872 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
875 // This codegen is a little surprising because we always call a shim
876 // function instead of inlining the call to `invoke` manually here. This is done
877 // because in LLVM we're only allowed to have one personality per function
878 // definition. The call to the `try` intrinsic is being inlined into the
879 // function calling it, and that function may already have other personality
880 // functions in play. By calling a shim we're guaranteed that our shim will have
881 // the right personality function.
883 bx: &Builder<'a, 'll, 'tcx>,
884 cx: &CodegenCx<'ll, 'tcx>,
887 local_ptr: &'ll Value,
890 let llfn = get_rust_try_fn(cx, &mut |bx| {
893 // Codegens the shims described above:
896 // invoke %func(%args...) normal %normal unwind %catch
902 // (ptr, _) = landingpad
903 // store ptr, %local_ptr
906 // Note that the `local_ptr` data passed into the `try` intrinsic is
907 // expected to be `*mut *mut u8` for this to actually work, but that's
908 // managed by the standard library.
910 let then = bx.build_sibling_block("then");
911 let catch = bx.build_sibling_block("catch");
913 let func = llvm::get_param(bx.llfn(), 0);
914 let data = llvm::get_param(bx.llfn(), 1);
915 let local_ptr = llvm::get_param(bx.llfn(), 2);
916 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
917 then.ret(C_i32(cx, 0));
919 // Type indicator for the exception being thrown.
921 // The first value in this tuple is a pointer to the exception object
922 // being thrown. The second value is a "selector" indicating which of
923 // the landing pad clauses the exception's type had been matched to.
924 // rust_try ignores the selector.
925 let lpad_ty = Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)], false);
926 let vals = catch.landing_pad(lpad_ty, bx.cx.eh_personality(), 1);
927 catch.add_clause(vals, C_null(Type::i8p(cx)));
928 let ptr = catch.extract_value(vals, 0);
929 let ptr_align = bx.tcx().data_layout.pointer_align;
930 catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(cx).ptr_to()), ptr_align);
931 catch.ret(C_i32(cx, 1));
934 // Note that no invoke is used here because by definition this function
935 // can't panic (that's what it's catching).
936 let ret = bx.call(llfn, &[func, data, local_ptr], None);
937 let i32_align = bx.tcx().data_layout.i32_align;
938 bx.store(ret, dest, i32_align);
941 // Helper function to give a Block to a closure to codegen a shim function.
942 // This is currently primarily used for the `try` intrinsic functions above.
943 fn gen_fn<'ll, 'tcx>(
944 cx: &CodegenCx<'ll, 'tcx>,
946 inputs: Vec<Ty<'tcx>>,
948 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
950 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
954 hir::Unsafety::Unsafe,
957 let llfn = declare::define_internal_fn(cx, name, rust_fn_sig);
958 attributes::from_fn_attrs(cx, llfn, None);
959 let bx = Builder::new_block(cx, llfn, "entry-block");
964 // Helper function used to get a handle to the `__rust_try` function used to
967 // This function is only generated once and is then cached.
968 fn get_rust_try_fn<'ll, 'tcx>(
969 cx: &CodegenCx<'ll, 'tcx>,
970 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
972 if let Some(llfn) = cx.rust_try_fn.get() {
976 // Define the type up front for the signature of the rust_try function.
978 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
979 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
983 hir::Unsafety::Unsafe,
986 let output = tcx.types.i32;
987 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
988 cx.rust_try_fn.set(Some(rust_try));
992 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
993 span_err!(a, b, E0511, "{}", c);
996 fn generic_simd_intrinsic(
997 bx: &Builder<'a, 'll, 'tcx>,
1000 args: &[OperandRef<'tcx, &'ll Value>],
1002 llret_ty: &'ll Type,
1004 ) -> Result<&'ll Value, ()> {
1005 // macros for error handling:
1006 macro_rules! emit_error {
1010 ($msg: tt, $($fmt: tt)*) => {
1011 span_invalid_monomorphization_error(
1013 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1018 macro_rules! return_error {
1021 emit_error!($($fmt)*);
1027 macro_rules! require {
1028 ($cond: expr, $($fmt: tt)*) => {
1030 return_error!($($fmt)*);
1035 macro_rules! require_simd {
1036 ($ty: expr, $position: expr) => {
1037 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1042 let sig = tcx.normalize_erasing_late_bound_regions(
1043 ty::ParamEnv::reveal_all(),
1044 &callee_ty.fn_sig(tcx),
1046 let arg_tys = sig.inputs();
1048 // every intrinsic takes a SIMD vector as its first argument
1049 require_simd!(arg_tys[0], "input");
1050 let in_ty = arg_tys[0];
1051 let in_elem = arg_tys[0].simd_type(tcx);
1052 let in_len = arg_tys[0].simd_size(tcx);
1054 let comparison = match name {
1055 "simd_eq" => Some(hir::BinOpKind::Eq),
1056 "simd_ne" => Some(hir::BinOpKind::Ne),
1057 "simd_lt" => Some(hir::BinOpKind::Lt),
1058 "simd_le" => Some(hir::BinOpKind::Le),
1059 "simd_gt" => Some(hir::BinOpKind::Gt),
1060 "simd_ge" => Some(hir::BinOpKind::Ge),
1064 if let Some(cmp_op) = comparison {
1065 require_simd!(ret_ty, "return");
1067 let out_len = ret_ty.simd_size(tcx);
1068 require!(in_len == out_len,
1069 "expected return type with length {} (same as input type `{}`), \
1070 found `{}` with length {}",
1073 require!(llret_ty.element_type().kind() == TypeKind::Integer,
1074 "expected return type with integer elements, found `{}` with non-integer `{}`",
1076 ret_ty.simd_type(tcx));
1078 return Ok(compare_simd_types(bx,
1079 args[0].immediate(),
1080 args[1].immediate(),
1086 if name.starts_with("simd_shuffle") {
1087 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1088 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1090 require_simd!(ret_ty, "return");
1092 let out_len = ret_ty.simd_size(tcx);
1093 require!(out_len == n,
1094 "expected return type of length {}, found `{}` with length {}",
1095 n, ret_ty, out_len);
1096 require!(in_elem == ret_ty.simd_type(tcx),
1097 "expected return element type `{}` (element of input `{}`), \
1098 found `{}` with element type `{}`",
1100 ret_ty, ret_ty.simd_type(tcx));
1102 let total_len = in_len as u128 * 2;
1104 let vector = args[2].immediate();
1106 let indices: Option<Vec<_>> = (0..n)
1109 let val = const_get_elt(vector, i as u64);
1110 match const_to_opt_u128(val, true) {
1112 emit_error!("shuffle index #{} is not a constant", arg_idx);
1115 Some(idx) if idx >= total_len => {
1116 emit_error!("shuffle index #{} is out of bounds (limit {})",
1117 arg_idx, total_len);
1120 Some(idx) => Some(C_i32(bx.cx, idx as i32)),
1124 let indices = match indices {
1126 None => return Ok(C_null(llret_ty))
1129 return Ok(bx.shuffle_vector(args[0].immediate(),
1130 args[1].immediate(),
1131 C_vector(&indices)))
1134 if name == "simd_insert" {
1135 require!(in_elem == arg_tys[2],
1136 "expected inserted type `{}` (element of input `{}`), found `{}`",
1137 in_elem, in_ty, arg_tys[2]);
1138 return Ok(bx.insert_element(args[0].immediate(),
1139 args[2].immediate(),
1140 args[1].immediate()))
1142 if name == "simd_extract" {
1143 require!(ret_ty == in_elem,
1144 "expected return type `{}` (element of input `{}`), found `{}`",
1145 in_elem, in_ty, ret_ty);
1146 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1149 if name == "simd_select" {
1150 let m_elem_ty = in_elem;
1152 let v_len = arg_tys[1].simd_size(tcx);
1153 require!(m_len == v_len,
1154 "mismatched lengths: mask length `{}` != other vector length `{}`",
1157 match m_elem_ty.sty {
1159 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1161 // truncate the mask to a vector of i1s
1162 let i1 = Type::i1(bx.cx);
1163 let i1xn = Type::vector::<Value>(i1, m_len as u64);
1164 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1165 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1168 fn simd_simple_float_intrinsic(
1170 in_elem: &::rustc::ty::TyS,
1171 in_ty: &::rustc::ty::TyS,
1173 bx: &Builder<'a, 'll, 'tcx>,
1175 args: &[OperandRef<'tcx, &'ll Value>],
1176 ) -> Result<&'ll Value, ()> {
1177 macro_rules! emit_error {
1181 ($msg: tt, $($fmt: tt)*) => {
1182 span_invalid_monomorphization_error(
1184 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1188 macro_rules! return_error {
1191 emit_error!($($fmt)*);
1196 let ety = match in_elem.sty {
1197 ty::Float(f) if f.bit_width() == 32 => {
1198 if in_len < 2 || in_len > 16 {
1200 "unsupported floating-point vector `{}` with length `{}` \
1201 out-of-range [2, 16]",
1206 ty::Float(f) if f.bit_width() == 64 => {
1207 if in_len < 2 || in_len > 8 {
1208 return_error!("unsupported floating-point vector `{}` with length `{}` \
1209 out-of-range [2, 8]",
1215 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1219 return_error!("`{}` is not a floating-point type", in_ty);
1223 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1224 let intrinsic = bx.cx.get_intrinsic(&llvm_name);
1225 let c = bx.call(intrinsic,
1226 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1228 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1234 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1237 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1240 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1243 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1246 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1249 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1252 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1255 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1258 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1261 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1264 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1267 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1270 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1273 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1275 _ => { /* fallthrough */ }
1279 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1280 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1281 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1282 let p0s: String = "p0".repeat(no_pointers);
1284 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1285 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1286 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1287 _ => unreachable!(),
1291 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1292 mut no_pointers: usize) -> &'ll Type {
1293 // FIXME: use cx.layout_of(ty).llvm_type() ?
1294 let mut elem_ty = match elem_ty.sty {
1295 ty::Int(v) => Type::int_from_ty(cx, v),
1296 ty::Uint(v) => Type::uint_from_ty(cx, v),
1297 ty::Float(v) => Type::float_from_ty(cx, v),
1298 _ => unreachable!(),
1300 while no_pointers > 0 {
1301 elem_ty = elem_ty.ptr_to();
1304 Type::vector::<Value>(elem_ty, vec_len as u64)
1308 if name == "simd_gather" {
1309 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1310 // mask: <N x i{M}>) -> <N x T>
1311 // * N: number of elements in the input vectors
1312 // * T: type of the element to load
1313 // * M: any integer width is supported, will be truncated to i1
1315 // All types must be simd vector types
1316 require_simd!(in_ty, "first");
1317 require_simd!(arg_tys[1], "second");
1318 require_simd!(arg_tys[2], "third");
1319 require_simd!(ret_ty, "return");
1321 // Of the same length:
1322 require!(in_len == arg_tys[1].simd_size(tcx),
1323 "expected {} argument with length {} (same as input type `{}`), \
1324 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1325 arg_tys[1].simd_size(tcx));
1326 require!(in_len == arg_tys[2].simd_size(tcx),
1327 "expected {} argument with length {} (same as input type `{}`), \
1328 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1329 arg_tys[2].simd_size(tcx));
1331 // The return type must match the first argument type
1332 require!(ret_ty == in_ty,
1333 "expected return type `{}`, found `{}`",
1336 // This counts how many pointers
1337 fn ptr_count(t: ty::Ty) -> usize {
1339 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1345 fn non_ptr(t: ty::Ty) -> ty::Ty {
1347 ty::RawPtr(p) => non_ptr(p.ty),
1352 // The second argument must be a simd vector with an element type that's a pointer
1353 // to the element type of the first argument
1354 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1355 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1356 non_ptr(arg_tys[1].simd_type(tcx))),
1358 require!(false, "expected element type `{}` of second argument `{}` \
1359 to be a pointer to the element type `{}` of the first \
1360 argument `{}`, found `{}` != `*_ {}`",
1361 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1362 arg_tys[1].simd_type(tcx).sty, in_elem);
1366 assert!(pointer_count > 0);
1367 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1368 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1370 // The element type of the third argument must be a signed integer type of any width:
1371 match arg_tys[2].simd_type(tcx).sty {
1374 require!(false, "expected element type `{}` of third argument `{}` \
1375 to be a signed integer type",
1376 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1380 // Alignment of T, must be a constant integer value:
1381 let alignment_ty = Type::i32(bx.cx);
1382 let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32);
1384 // Truncate the mask vector to a vector of i1s:
1385 let (mask, mask_ty) = {
1386 let i1 = Type::i1(bx.cx);
1387 let i1xn = Type::vector::<Value>(i1, in_len as u64);
1388 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1391 // Type of the vector of pointers:
1392 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count);
1393 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1395 // Type of the vector of elements:
1396 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1);
1397 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1399 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1400 llvm_elem_vec_str, llvm_pointer_vec_str);
1401 let f = declare::declare_cfn(bx.cx, &llvm_intrinsic,
1402 Type::func::<Value>(&[
1403 llvm_pointer_vec_ty,
1406 llvm_elem_vec_ty], llvm_elem_vec_ty));
1407 llvm::SetUnnamedAddr(f, false);
1408 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1413 if name == "simd_scatter" {
1414 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1415 // mask: <N x i{M}>) -> ()
1416 // * N: number of elements in the input vectors
1417 // * T: type of the element to load
1418 // * M: any integer width is supported, will be truncated to i1
1420 // All types must be simd vector types
1421 require_simd!(in_ty, "first");
1422 require_simd!(arg_tys[1], "second");
1423 require_simd!(arg_tys[2], "third");
1425 // Of the same length:
1426 require!(in_len == arg_tys[1].simd_size(tcx),
1427 "expected {} argument with length {} (same as input type `{}`), \
1428 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1429 arg_tys[1].simd_size(tcx));
1430 require!(in_len == arg_tys[2].simd_size(tcx),
1431 "expected {} argument with length {} (same as input type `{}`), \
1432 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1433 arg_tys[2].simd_size(tcx));
1435 // This counts how many pointers
1436 fn ptr_count(t: ty::Ty) -> usize {
1438 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1444 fn non_ptr(t: ty::Ty) -> ty::Ty {
1446 ty::RawPtr(p) => non_ptr(p.ty),
1451 // The second argument must be a simd vector with an element type that's a pointer
1452 // to the element type of the first argument
1453 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1454 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1455 => (ptr_count(arg_tys[1].simd_type(tcx)),
1456 non_ptr(arg_tys[1].simd_type(tcx))),
1458 require!(false, "expected element type `{}` of second argument `{}` \
1459 to be a pointer to the element type `{}` of the first \
1460 argument `{}`, found `{}` != `*mut {}`",
1461 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1462 arg_tys[1].simd_type(tcx).sty, in_elem);
1466 assert!(pointer_count > 0);
1467 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1468 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1470 // The element type of the third argument must be a signed integer type of any width:
1471 match arg_tys[2].simd_type(tcx).sty {
1474 require!(false, "expected element type `{}` of third argument `{}` \
1475 to be a signed integer type",
1476 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1480 // Alignment of T, must be a constant integer value:
1481 let alignment_ty = Type::i32(bx.cx);
1482 let alignment = C_i32(bx.cx, bx.cx.align_of(in_elem).abi() as i32);
1484 // Truncate the mask vector to a vector of i1s:
1485 let (mask, mask_ty) = {
1486 let i1 = Type::i1(bx.cx);
1487 let i1xn = Type::vector::<Value>(i1, in_len as u64);
1488 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1491 let ret_t = Type::void(bx.cx);
1493 // Type of the vector of pointers:
1494 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count);
1495 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1497 // Type of the vector of elements:
1498 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx, underlying_ty, in_len, pointer_count - 1);
1499 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1501 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1502 llvm_elem_vec_str, llvm_pointer_vec_str);
1503 let f = declare::declare_cfn(bx.cx, &llvm_intrinsic,
1504 Type::func::<Value>(&[llvm_elem_vec_ty,
1505 llvm_pointer_vec_ty,
1508 llvm::SetUnnamedAddr(f, false);
1509 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1514 macro_rules! arith_red {
1515 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1517 require!(ret_ty == in_elem,
1518 "expected return type `{}` (element of input `{}`), found `{}`",
1519 in_elem, in_ty, ret_ty);
1520 return match in_elem.sty {
1521 ty::Int(_) | ty::Uint(_) => {
1522 let r = bx.$integer_reduce(args[0].immediate());
1524 // if overflow occurs, the result is the
1525 // mathematical result modulo 2^n:
1526 if name.contains("mul") {
1527 Ok(bx.mul(args[1].immediate(), r))
1529 Ok(bx.add(args[1].immediate(), r))
1532 Ok(bx.$integer_reduce(args[0].immediate()))
1536 // ordered arithmetic reductions take an accumulator
1537 let acc = if $ordered {
1538 let acc = args[1].immediate();
1539 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1540 // * if the accumulator of the fadd isn't 0, incorrect
1541 // code is generated
1542 // * if the accumulator of the fmul isn't 1, incorrect
1543 // code is generated
1544 match const_get_real(acc) {
1545 None => return_error!("accumulator of {} is not a constant", $name),
1546 Some((v, loses_info)) => {
1547 if $name.contains("mul") && v != 1.0_f64 {
1548 return_error!("accumulator of {} is not 1.0", $name);
1549 } else if $name.contains("add") && v != 0.0_f64 {
1550 return_error!("accumulator of {} is not 0.0", $name);
1551 } else if loses_info {
1552 return_error!("accumulator of {} loses information", $name);
1558 // unordered arithmetic reductions do not:
1559 match f.bit_width() {
1560 32 => C_undef(Type::f32(bx.cx)),
1561 64 => C_undef(Type::f64(bx.cx)),
1564 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1565 $name, in_ty, in_elem, v, ret_ty
1570 Ok(bx.$float_reduce(acc, args[0].immediate()))
1574 "unsupported {} from `{}` with element `{}` to `{}`",
1575 $name, in_ty, in_elem, ret_ty
1583 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1584 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1585 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1586 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1588 macro_rules! minmax_red {
1589 ($name:tt: $int_red:ident, $float_red:ident) => {
1591 require!(ret_ty == in_elem,
1592 "expected return type `{}` (element of input `{}`), found `{}`",
1593 in_elem, in_ty, ret_ty);
1594 return match in_elem.sty {
1596 Ok(bx.$int_red(args[0].immediate(), true))
1599 Ok(bx.$int_red(args[0].immediate(), false))
1602 Ok(bx.$float_red(args[0].immediate()))
1605 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1606 $name, in_ty, in_elem, ret_ty)
1614 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1615 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1617 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1618 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1620 macro_rules! bitwise_red {
1621 ($name:tt : $red:ident, $boolean:expr) => {
1623 let input = if !$boolean {
1624 require!(ret_ty == in_elem,
1625 "expected return type `{}` (element of input `{}`), found `{}`",
1626 in_elem, in_ty, ret_ty);
1630 ty::Int(_) | ty::Uint(_) => {},
1632 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1633 $name, in_ty, in_elem, ret_ty)
1637 // boolean reductions operate on vectors of i1s:
1638 let i1 = Type::i1(bx.cx);
1639 let i1xn = Type::vector::<Value>(i1, in_len as u64);
1640 bx.trunc(args[0].immediate(), i1xn)
1642 return match in_elem.sty {
1643 ty::Int(_) | ty::Uint(_) => {
1644 let r = bx.$red(input);
1649 bx.zext(r, Type::bool(bx.cx))
1654 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1655 $name, in_ty, in_elem, ret_ty)
1662 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1663 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1664 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1665 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1666 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1668 if name == "simd_cast" {
1669 require_simd!(ret_ty, "return");
1670 let out_len = ret_ty.simd_size(tcx);
1671 require!(in_len == out_len,
1672 "expected return type with length {} (same as input type `{}`), \
1673 found `{}` with length {}",
1676 // casting cares about nominal type, not just structural type
1677 let out_elem = ret_ty.simd_type(tcx);
1679 if in_elem == out_elem { return Ok(args[0].immediate()); }
1681 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1683 let (in_style, in_width) = match in_elem.sty {
1684 // vectors of pointer-sized integers should've been
1685 // disallowed before here, so this unwrap is safe.
1686 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1687 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1688 ty::Float(f) => (Style::Float, f.bit_width()),
1689 _ => (Style::Unsupported, 0)
1691 let (out_style, out_width) = match out_elem.sty {
1692 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1693 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1694 ty::Float(f) => (Style::Float, f.bit_width()),
1695 _ => (Style::Unsupported, 0)
1698 match (in_style, out_style) {
1699 (Style::Int(in_is_signed), Style::Int(_)) => {
1700 return Ok(match in_width.cmp(&out_width) {
1701 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1702 Ordering::Equal => args[0].immediate(),
1703 Ordering::Less => if in_is_signed {
1704 bx.sext(args[0].immediate(), llret_ty)
1706 bx.zext(args[0].immediate(), llret_ty)
1710 (Style::Int(in_is_signed), Style::Float) => {
1711 return Ok(if in_is_signed {
1712 bx.sitofp(args[0].immediate(), llret_ty)
1714 bx.uitofp(args[0].immediate(), llret_ty)
1717 (Style::Float, Style::Int(out_is_signed)) => {
1718 return Ok(if out_is_signed {
1719 bx.fptosi(args[0].immediate(), llret_ty)
1721 bx.fptoui(args[0].immediate(), llret_ty)
1724 (Style::Float, Style::Float) => {
1725 return Ok(match in_width.cmp(&out_width) {
1726 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1727 Ordering::Equal => args[0].immediate(),
1728 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1731 _ => {/* Unsupported. Fallthrough. */}
1734 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1738 macro_rules! arith {
1739 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1740 $(if name == stringify!($name) {
1742 $($(ty::$p(_))|* => {
1743 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1748 "unsupported operation on `{}` with element `{}`",
1755 simd_add: Uint, Int => add, Float => fadd;
1756 simd_sub: Uint, Int => sub, Float => fsub;
1757 simd_mul: Uint, Int => mul, Float => fmul;
1758 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1759 simd_rem: Uint => urem, Int => srem, Float => frem;
1760 simd_shl: Uint, Int => shl;
1761 simd_shr: Uint => lshr, Int => ashr;
1762 simd_and: Uint, Int => and;
1763 simd_or: Uint, Int => or;
1764 simd_xor: Uint, Int => xor;
1765 simd_fmax: Float => maxnum;
1766 simd_fmin: Float => minnum;
1768 span_bug!(span, "unknown SIMD intrinsic");
1771 // Returns the width of an int Ty, and if it's signed or not
1772 // Returns None if the type is not an integer
1773 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1775 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1777 ty::Int(t) => Some((match t {
1778 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1779 ast::IntTy::I8 => 8,
1780 ast::IntTy::I16 => 16,
1781 ast::IntTy::I32 => 32,
1782 ast::IntTy::I64 => 64,
1783 ast::IntTy::I128 => 128,
1785 ty::Uint(t) => Some((match t {
1786 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1787 ast::UintTy::U8 => 8,
1788 ast::UintTy::U16 => 16,
1789 ast::UintTy::U32 => 32,
1790 ast::UintTy::U64 => 64,
1791 ast::UintTy::U128 => 128,
1797 // Returns the width of a float TypeVariant
1798 // Returns None if the type is not a float
1799 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1801 ty::Float(t) => Some(t.bit_width() as u64),