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, HasTyCtxt};
31 use syntax::symbol::Symbol;
32 use builder::{Builder, MemFlags};
37 use rustc::session::Session;
40 use std::cmp::Ordering;
43 fn get_simple_intrinsic(cx: &CodegenCx<'ll, '_>, name: &str) -> Option<&'ll Value> {
44 let llvm_name = match name {
45 "sqrtf32" => "llvm.sqrt.f32",
46 "sqrtf64" => "llvm.sqrt.f64",
47 "powif32" => "llvm.powi.f32",
48 "powif64" => "llvm.powi.f64",
49 "sinf32" => "llvm.sin.f32",
50 "sinf64" => "llvm.sin.f64",
51 "cosf32" => "llvm.cos.f32",
52 "cosf64" => "llvm.cos.f64",
53 "powf32" => "llvm.pow.f32",
54 "powf64" => "llvm.pow.f64",
55 "expf32" => "llvm.exp.f32",
56 "expf64" => "llvm.exp.f64",
57 "exp2f32" => "llvm.exp2.f32",
58 "exp2f64" => "llvm.exp2.f64",
59 "logf32" => "llvm.log.f32",
60 "logf64" => "llvm.log.f64",
61 "log10f32" => "llvm.log10.f32",
62 "log10f64" => "llvm.log10.f64",
63 "log2f32" => "llvm.log2.f32",
64 "log2f64" => "llvm.log2.f64",
65 "fmaf32" => "llvm.fma.f32",
66 "fmaf64" => "llvm.fma.f64",
67 "fabsf32" => "llvm.fabs.f32",
68 "fabsf64" => "llvm.fabs.f64",
69 "copysignf32" => "llvm.copysign.f32",
70 "copysignf64" => "llvm.copysign.f64",
71 "floorf32" => "llvm.floor.f32",
72 "floorf64" => "llvm.floor.f64",
73 "ceilf32" => "llvm.ceil.f32",
74 "ceilf64" => "llvm.ceil.f64",
75 "truncf32" => "llvm.trunc.f32",
76 "truncf64" => "llvm.trunc.f64",
77 "rintf32" => "llvm.rint.f32",
78 "rintf64" => "llvm.rint.f64",
79 "nearbyintf32" => "llvm.nearbyint.f32",
80 "nearbyintf64" => "llvm.nearbyint.f64",
81 "roundf32" => "llvm.round.f32",
82 "roundf64" => "llvm.round.f64",
83 "assume" => "llvm.assume",
84 "abort" => "llvm.trap",
87 Some(cx.get_intrinsic(&llvm_name))
90 impl IntrinsicCallMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
91 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
92 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
93 /// add them to librustc_codegen_llvm/context.rs
94 fn codegen_intrinsic_call(
97 fn_ty: &FnType<'tcx, Ty<'tcx>>,
98 args: &[OperandRef<'tcx, &'ll Value>],
105 let (def_id, substs) = match callee_ty.sty {
106 ty::FnDef(def_id, substs) => (def_id, substs),
107 _ => bug!("expected fn item type, found {}", callee_ty)
110 let sig = callee_ty.fn_sig(tcx);
111 let sig = tcx.normalize_erasing_late_bound_regions(ty::ParamEnv::reveal_all(), &sig);
112 let arg_tys = sig.inputs();
113 let ret_ty = sig.output();
114 let name = &*tcx.item_name(def_id).as_str();
116 let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
117 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
119 let simple = get_simple_intrinsic(cx, name);
120 let llval = match name {
121 _ if simple.is_some() => {
122 self.call(simple.unwrap(),
123 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
130 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
131 self.call(expect, &[args[0].immediate(), cx.const_bool(true)], None)
134 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
135 self.call(expect, &[args[0].immediate(), cx.const_bool(false)], None)
138 try_intrinsic(self, cx,
146 let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
147 self.call(llfn, &[], None)
150 let tp_ty = substs.type_at(0);
151 cx.const_usize(cx.size_of(tp_ty).bytes())
154 let tp_ty = substs.type_at(0);
155 if let OperandValue::Pair(_, meta) = args[0].val {
157 glue::size_and_align_of_dst(&self, tp_ty, Some(meta));
160 cx.const_usize(cx.size_of(tp_ty).bytes())
164 let tp_ty = substs.type_at(0);
165 cx.const_usize(cx.align_of(tp_ty).abi())
167 "min_align_of_val" => {
168 let tp_ty = substs.type_at(0);
169 if let OperandValue::Pair(_, meta) = args[0].val {
171 glue::size_and_align_of_dst(&self, tp_ty, Some(meta));
174 cx.const_usize(cx.align_of(tp_ty).abi())
178 let tp_ty = substs.type_at(0);
179 cx.const_usize(cx.align_of(tp_ty).pref())
182 let tp_ty = substs.type_at(0);
183 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
184 cx.const_str_slice(ty_name)
187 cx.const_u64(cx.tcx.type_id_hash(substs.type_at(0)))
190 let ty = substs.type_at(0);
191 if !cx.layout_of(ty).is_zst() {
192 // Just zero out the stack slot.
193 // If we store a zero constant, LLVM will drown in vreg allocation for large
194 // data structures, and the generated code will be awful. (A telltale sign of
195 // this is large quantities of `mov [byte ptr foo],0` in the generated code.)
207 // Effectively no-ops
208 "uninit" | "forget" => {
212 let tp_ty = substs.type_at(0);
214 cx.const_bool(cx.type_needs_drop(tp_ty))
217 let ptr = args[0].immediate();
218 let offset = args[1].immediate();
219 self.inbounds_gep(ptr, &[offset])
222 let ptr = args[0].immediate();
223 let offset = args[1].immediate();
224 self.gep(ptr, &[offset])
227 "copy_nonoverlapping" => {
228 copy_intrinsic(&self, false, false, substs.type_at(0),
229 args[1].immediate(), args[0].immediate(), args[2].immediate());
233 copy_intrinsic(&self, true, false, substs.type_at(0),
234 args[1].immediate(), args[0].immediate(), args[2].immediate());
238 memset_intrinsic(&self, false, substs.type_at(0),
239 args[0].immediate(), args[1].immediate(), args[2].immediate());
243 "volatile_copy_nonoverlapping_memory" => {
244 copy_intrinsic(&self, false, true, substs.type_at(0),
245 args[0].immediate(), args[1].immediate(), args[2].immediate());
248 "volatile_copy_memory" => {
249 copy_intrinsic(&self, true, true, substs.type_at(0),
250 args[0].immediate(), args[1].immediate(), args[2].immediate());
253 "volatile_set_memory" => {
254 memset_intrinsic(&self, true, substs.type_at(0),
255 args[0].immediate(), args[1].immediate(), args[2].immediate());
258 "volatile_load" | "unaligned_volatile_load" => {
259 let tp_ty = substs.type_at(0);
260 let mut ptr = args[0].immediate();
261 if let PassMode::Cast(ty) = fn_ty.ret.mode {
262 ptr = self.pointercast(ptr, cx.type_ptr_to(ty.llvm_type(cx)));
264 let load = self.volatile_load(ptr);
265 let align = if name == "unaligned_volatile_load" {
268 cx.align_of(tp_ty).abi() as u32
271 llvm::LLVMSetAlignment(load, align);
273 to_immediate(self, load, cx.layout_of(tp_ty))
275 "volatile_store" => {
276 let dst = args[0].deref(cx);
277 args[1].val.volatile_store(&self, dst);
280 "unaligned_volatile_store" => {
281 let dst = args[0].deref(cx);
282 args[1].val.unaligned_volatile_store(&self, dst);
285 "prefetch_read_data" | "prefetch_write_data" |
286 "prefetch_read_instruction" | "prefetch_write_instruction" => {
287 let expect = cx.get_intrinsic(&("llvm.prefetch"));
288 let (rw, cache_type) = match name {
289 "prefetch_read_data" => (0, 1),
290 "prefetch_write_data" => (1, 1),
291 "prefetch_read_instruction" => (0, 0),
292 "prefetch_write_instruction" => (1, 0),
299 cx.const_i32(cache_type)
302 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
303 "bitreverse" | "add_with_overflow" | "sub_with_overflow" |
304 "mul_with_overflow" | "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
305 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" | "exact_div" |
306 "rotate_left" | "rotate_right" => {
308 match int_type_width_signed(ty, cx) {
309 Some((width, signed)) =>
312 let y = cx.const_bool(false);
313 let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
314 self.call(llfn, &[args[0].immediate(), y], None)
316 "ctlz_nonzero" | "cttz_nonzero" => {
317 let y = cx.const_bool(true);
318 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
319 let llfn = cx.get_intrinsic(llvm_name);
320 self.call(llfn, &[args[0].immediate(), y], None)
322 "ctpop" => self.call(
323 cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
324 &[args[0].immediate()],
329 args[0].immediate() // byte swap a u8/i8 is just a no-op
331 self.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
332 &[args[0].immediate()], None)
336 self.call(cx.get_intrinsic(&format!("llvm.bitreverse.i{}", width)),
337 &[args[0].immediate()], None)
339 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
340 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
341 if signed { 's' } else { 'u' },
343 let llfn = cx.get_intrinsic(&intrinsic);
345 // Convert `i1` to a `bool`, and write it to the out parameter
346 let pair = self.call(llfn, &[
350 let val = self.extract_value(pair, 0);
351 let overflow = self.zext(
352 self.extract_value(pair, 1),
356 let dest = result.project_field(&self, 0);
357 self.store(val, dest.llval, dest.align);
358 let dest = result.project_field(&self, 1);
359 self.store(overflow, dest.llval, dest.align);
363 "overflowing_add" => self.add(args[0].immediate(), args[1].immediate()),
364 "overflowing_sub" => self.sub(args[0].immediate(), args[1].immediate()),
365 "overflowing_mul" => self.mul(args[0].immediate(), args[1].immediate()),
368 self.exactsdiv(args[0].immediate(), args[1].immediate())
370 self.exactudiv(args[0].immediate(), args[1].immediate())
374 self.sdiv(args[0].immediate(), args[1].immediate())
376 self.udiv(args[0].immediate(), args[1].immediate())
380 self.srem(args[0].immediate(), args[1].immediate())
382 self.urem(args[0].immediate(), args[1].immediate())
384 "unchecked_shl" => self.shl(args[0].immediate(), args[1].immediate()),
387 self.ashr(args[0].immediate(), args[1].immediate())
389 self.lshr(args[0].immediate(), args[1].immediate())
391 "rotate_left" | "rotate_right" => {
392 let is_left = name == "rotate_left";
393 let val = args[0].immediate();
394 let raw_shift = args[1].immediate();
395 if llvm_util::get_major_version() >= 7 {
396 // rotate = funnel shift with first two args the same
397 let llvm_name = &format!("llvm.fsh{}.i{}",
398 if is_left { 'l' } else { 'r' }, width);
399 let llfn = cx.get_intrinsic(llvm_name);
400 self.call(llfn, &[val, val, raw_shift], None)
402 // rotate_left: (X << (S % BW)) | (X >> ((BW - S) % BW))
403 // rotate_right: (X << ((BW - S) % BW)) | (X >> (S % BW))
404 let width = cx.const_uint(cx.type_ix(width), width);
405 let shift = self.urem(raw_shift, width);
406 let inv_shift = self.urem(self.sub(width, raw_shift), width);
407 let shift1 = self.shl(
409 if is_left { shift } else { inv_shift },
411 let shift2 = self.lshr(
413 if !is_left { shift } else { inv_shift },
415 self.or(shift1, shift2)
421 span_invalid_monomorphization_error(
423 &format!("invalid monomorphization of `{}` intrinsic: \
424 expected basic integer type, found `{}`", name, ty));
430 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
431 let sty = &arg_tys[0].sty;
432 match float_type_width(sty) {
435 "fadd_fast" => self.fadd_fast(args[0].immediate(), args[1].immediate()),
436 "fsub_fast" => self.fsub_fast(args[0].immediate(), args[1].immediate()),
437 "fmul_fast" => self.fmul_fast(args[0].immediate(), args[1].immediate()),
438 "fdiv_fast" => self.fdiv_fast(args[0].immediate(), args[1].immediate()),
439 "frem_fast" => self.frem_fast(args[0].immediate(), args[1].immediate()),
443 span_invalid_monomorphization_error(
445 &format!("invalid monomorphization of `{}` intrinsic: \
446 expected basic float type, found `{}`", name, sty));
453 "discriminant_value" => {
454 args[0].deref(cx).codegen_get_discr(&self, ret_ty)
457 name if name.starts_with("simd_") => {
458 match generic_simd_intrinsic(&self, name,
467 // This requires that atomic intrinsics follow a specific naming pattern:
468 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
469 name if name.starts_with("atomic_") => {
470 use self::AtomicOrdering::*;
472 let split: Vec<&str> = name.split('_').collect();
474 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
475 let (order, failorder) = match split.len() {
476 2 => (SequentiallyConsistent, SequentiallyConsistent),
477 3 => match split[2] {
478 "unordered" => (Unordered, Unordered),
479 "relaxed" => (Monotonic, Monotonic),
480 "acq" => (Acquire, Acquire),
481 "rel" => (Release, Monotonic),
482 "acqrel" => (AcquireRelease, Acquire),
483 "failrelaxed" if is_cxchg =>
484 (SequentiallyConsistent, Monotonic),
485 "failacq" if is_cxchg =>
486 (SequentiallyConsistent, Acquire),
487 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
489 4 => match (split[2], split[3]) {
490 ("acq", "failrelaxed") if is_cxchg =>
491 (Acquire, Monotonic),
492 ("acqrel", "failrelaxed") if is_cxchg =>
493 (AcquireRelease, Monotonic),
494 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
496 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
499 let invalid_monomorphization = |ty| {
500 span_invalid_monomorphization_error(tcx.sess, span,
501 &format!("invalid monomorphization of `{}` intrinsic: \
502 expected basic integer type, found `{}`", name, ty));
506 "cxchg" | "cxchgweak" => {
507 let ty = substs.type_at(0);
508 if int_type_width_signed(ty, cx).is_some() {
509 let weak = split[1] == "cxchgweak";
510 let pair = self.atomic_cmpxchg(
517 let val = self.extract_value(pair, 0);
518 let success = self.zext(
519 self.extract_value(pair, 1),
523 let dest = result.project_field(&self, 0);
524 self.store(val, dest.llval, dest.align);
525 let dest = result.project_field(&self, 1);
526 self.store(success, dest.llval, dest.align);
529 return invalid_monomorphization(ty);
534 let ty = substs.type_at(0);
535 if int_type_width_signed(ty, cx).is_some() {
536 let size = cx.size_of(ty);
537 self.atomic_load(args[0].immediate(), order, size)
539 return invalid_monomorphization(ty);
544 let ty = substs.type_at(0);
545 if int_type_width_signed(ty, cx).is_some() {
546 let size = cx.size_of(ty);
555 return invalid_monomorphization(ty);
560 self.atomic_fence(order, SynchronizationScope::CrossThread);
564 "singlethreadfence" => {
565 self.atomic_fence(order, SynchronizationScope::SingleThread);
569 // These are all AtomicRMW ops
571 let atom_op = match op {
572 "xchg" => AtomicRmwBinOp::AtomicXchg,
573 "xadd" => AtomicRmwBinOp::AtomicAdd,
574 "xsub" => AtomicRmwBinOp::AtomicSub,
575 "and" => AtomicRmwBinOp::AtomicAnd,
576 "nand" => AtomicRmwBinOp::AtomicNand,
577 "or" => AtomicRmwBinOp::AtomicOr,
578 "xor" => AtomicRmwBinOp::AtomicXor,
579 "max" => AtomicRmwBinOp::AtomicMax,
580 "min" => AtomicRmwBinOp::AtomicMin,
581 "umax" => AtomicRmwBinOp::AtomicUMax,
582 "umin" => AtomicRmwBinOp::AtomicUMin,
583 _ => cx.sess().fatal("unknown atomic operation")
586 let ty = substs.type_at(0);
587 if int_type_width_signed(ty, cx).is_some() {
595 return invalid_monomorphization(ty);
601 "nontemporal_store" => {
602 let dst = args[0].deref(cx);
603 args[1].val.nontemporal_store(&self, dst);
608 let intr = match Intrinsic::find(&name) {
610 None => bug!("unknown intrinsic '{}'", name),
612 fn one<T>(x: Vec<T>) -> T {
613 assert_eq!(x.len(), 1);
614 x.into_iter().next().unwrap()
617 cx: &CodegenCx<'ll, '_>,
619 ) -> Vec<&'ll Type> {
620 use intrinsics::Type::*;
622 Void => vec![cx.type_void()],
623 Integer(_signed, _width, llvm_width) => {
624 vec![cx.type_ix( llvm_width as u64)]
628 32 => vec![cx.type_f32()],
629 64 => vec![cx.type_f64()],
633 Pointer(ref t, ref llvm_elem, _const) => {
634 let t = llvm_elem.as_ref().unwrap_or(t);
635 let elem = one(ty_to_type(cx, t));
636 vec![cx.type_ptr_to(elem)]
638 Vector(ref t, ref llvm_elem, length) => {
639 let t = llvm_elem.as_ref().unwrap_or(t);
640 let elem = one(ty_to_type(cx, t));
641 vec![cx.type_vector(elem, length as u64)]
643 Aggregate(false, ref contents) => {
644 let elems = contents.iter()
645 .map(|t| one(ty_to_type(cx, t)))
646 .collect::<Vec<_>>();
647 vec![cx.type_struct( &elems, false)]
649 Aggregate(true, ref contents) => {
651 .flat_map(|t| ty_to_type(cx, t))
657 // This allows an argument list like `foo, (bar, baz),
658 // qux` to be converted into `foo, bar, baz, qux`, integer
659 // arguments to be truncated as needed and pointers to be
661 fn modify_as_needed<'ll, 'tcx>(
662 bx: &Builder<'_, 'll, 'tcx>,
663 t: &intrinsics::Type,
664 arg: &OperandRef<'tcx, &'ll Value>,
665 ) -> Vec<&'ll Value> {
667 intrinsics::Type::Aggregate(true, ref contents) => {
668 // We found a tuple that needs squishing! So
669 // run over the tuple and load each field.
671 // This assumes the type is "simple", i.e. no
672 // destructors, and the contents are SIMD
674 assert!(!bx.cx().type_needs_drop(arg.layout.ty));
675 let (ptr, align) = match arg.val {
676 OperandValue::Ref(ptr, None, align) => (ptr, align),
679 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
680 (0..contents.len()).map(|i| {
681 arg.project_field(bx, i).load(bx).immediate()
684 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
685 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
686 vec![bx.pointercast(arg.immediate(), bx.cx().type_ptr_to(llvm_elem))]
688 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
689 let llvm_elem = one(ty_to_type(bx.cx(), llvm_elem));
691 bx.bitcast(arg.immediate(),
692 bx.cx().type_vector(llvm_elem, length as u64))
695 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
696 // the LLVM intrinsic uses a smaller integer
697 // size than the C intrinsic's signature, so
698 // we have to trim it down here.
699 vec![bx.trunc(arg.immediate(), bx.cx().type_ix(llvm_width as u64))]
701 _ => vec![arg.immediate()],
706 let inputs = intr.inputs.iter()
707 .flat_map(|t| ty_to_type(cx, t))
708 .collect::<Vec<_>>();
710 let outputs = one(ty_to_type(cx, &intr.output));
712 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
713 modify_as_needed(&self, t, arg)
715 assert_eq!(inputs.len(), llargs.len());
717 let val = match intr.definition {
718 intrinsics::IntrinsicDef::Named(name) => {
719 let f = declare::declare_cfn(cx,
721 cx.type_func(&inputs, outputs));
722 self.call(f, &llargs, None)
727 intrinsics::Type::Aggregate(flatten, ref elems) => {
728 // the output is a tuple so we need to munge it properly
731 for i in 0..elems.len() {
732 let dest = result.project_field(&self, i);
733 let val = self.extract_value(val, i as u64);
734 self.store(val, dest.llval, dest.align);
743 if !fn_ty.ret.is_ignore() {
744 if let PassMode::Cast(ty) = fn_ty.ret.mode {
745 let ptr = self.pointercast(result.llval, cx.type_ptr_to(ty.llvm_type(cx)));
746 self.store(llval, ptr, result.align);
748 OperandRef::from_immediate_or_packed_pair(&self, llval, result.layout)
749 .val.store(&self, result);
756 bx: &Builder<'a, 'll, 'tcx>,
764 let (size, align) = bx.cx().size_and_align_of(ty);
765 let size = bx.mul(bx.cx().const_usize(size.bytes()), count);
766 let flags = if volatile {
772 bx.memmove(dst, align, src, align, size, flags);
774 bx.memcpy(dst, align, src, align, size, flags);
779 bx: &Builder<'a, 'll, 'tcx>,
786 let (size, align) = bx.cx().size_and_align_of(ty);
787 let size = bx.cx().const_usize(size.bytes());
788 let flags = if volatile {
793 bx.memset(dst, val, bx.mul(size, count), align, flags);
797 bx: &Builder<'a, 'll, 'tcx>,
798 cx: &CodegenCx<'ll, 'tcx>,
801 local_ptr: &'ll Value,
804 if bx.sess().no_landing_pads() {
805 bx.call(func, &[data], None);
806 let ptr_align = bx.tcx().data_layout.pointer_align;
807 bx.store(cx.const_null(cx.type_i8p()), dest, ptr_align);
808 } else if wants_msvc_seh(bx.sess()) {
809 codegen_msvc_try(bx, cx, func, data, local_ptr, dest);
811 codegen_gnu_try(bx, cx, func, data, local_ptr, dest);
815 // MSVC's definition of the `rust_try` function.
817 // This implementation uses the new exception handling instructions in LLVM
818 // which have support in LLVM for SEH on MSVC targets. Although these
819 // instructions are meant to work for all targets, as of the time of this
820 // writing, however, LLVM does not recommend the usage of these new instructions
821 // as the old ones are still more optimized.
823 bx: &Builder<'a, 'll, 'tcx>,
824 cx: &CodegenCx<'ll, 'tcx>,
827 local_ptr: &'ll Value,
830 let llfn = get_rust_try_fn(cx, &mut |bx| {
833 bx.set_personality_fn(bx.cx().eh_personality());
835 let normal = bx.build_sibling_block("normal");
836 let catchswitch = bx.build_sibling_block("catchswitch");
837 let catchpad = bx.build_sibling_block("catchpad");
838 let caught = bx.build_sibling_block("caught");
840 let func = llvm::get_param(bx.llfn(), 0);
841 let data = llvm::get_param(bx.llfn(), 1);
842 let local_ptr = llvm::get_param(bx.llfn(), 2);
844 // We're generating an IR snippet that looks like:
846 // declare i32 @rust_try(%func, %data, %ptr) {
847 // %slot = alloca i64*
848 // invoke %func(%data) to label %normal unwind label %catchswitch
854 // %cs = catchswitch within none [%catchpad] unwind to caller
857 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
858 // %ptr[0] = %slot[0]
859 // %ptr[1] = %slot[1]
860 // catchret from %tok to label %caught
866 // This structure follows the basic usage of throw/try/catch in LLVM.
867 // For example, compile this C++ snippet to see what LLVM generates:
869 // #include <stdint.h>
871 // int bar(void (*foo)(void), uint64_t *ret) {
875 // } catch(uint64_t a[2]) {
882 // More information can be found in libstd's seh.rs implementation.
883 let i64p = cx.type_ptr_to(cx.type_i64());
884 let ptr_align = bx.tcx().data_layout.pointer_align;
885 let slot = bx.alloca(i64p, "slot", ptr_align);
886 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(), None);
888 normal.ret(cx.const_i32(0));
890 let cs = catchswitch.catch_switch(None, None, 1);
891 catchswitch.add_handler(cs, catchpad.llbb());
894 let tydesc = match tcx.lang_items().msvc_try_filter() {
895 Some(did) => cx.get_static(did),
896 None => bug!("msvc_try_filter not defined"),
898 let tok = catchpad.catch_pad(cs, &[tydesc, cx.const_i32(0), slot]);
899 let addr = catchpad.load(slot, ptr_align);
901 let i64_align = bx.tcx().data_layout.i64_align;
902 let arg1 = catchpad.load(addr, i64_align);
903 let val1 = cx.const_i32(1);
904 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
905 let local_ptr = catchpad.bitcast(local_ptr, i64p);
906 catchpad.store(arg1, local_ptr, i64_align);
907 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
908 catchpad.catch_ret(tok, caught.llbb());
910 caught.ret(cx.const_i32(1));
913 // Note that no invoke is used here because by definition this function
914 // can't panic (that's what it's catching).
915 let ret = bx.call(llfn, &[func, data, local_ptr], None);
916 let i32_align = bx.tcx().data_layout.i32_align;
917 bx.store(ret, dest, i32_align);
920 // Definition of the standard "try" function for Rust using the GNU-like model
921 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
924 // This codegen is a little surprising because we always call a shim
925 // function instead of inlining the call to `invoke` manually here. This is done
926 // because in LLVM we're only allowed to have one personality per function
927 // definition. The call to the `try` intrinsic is being inlined into the
928 // function calling it, and that function may already have other personality
929 // functions in play. By calling a shim we're guaranteed that our shim will have
930 // the right personality function.
932 bx: &Builder<'a, 'll, 'tcx>,
933 cx: &CodegenCx<'ll, 'tcx>,
936 local_ptr: &'ll Value,
939 let llfn = get_rust_try_fn(cx, &mut |bx| {
942 // Codegens the shims described above:
945 // invoke %func(%args...) normal %normal unwind %catch
951 // (ptr, _) = landingpad
952 // store ptr, %local_ptr
955 // Note that the `local_ptr` data passed into the `try` intrinsic is
956 // expected to be `*mut *mut u8` for this to actually work, but that's
957 // managed by the standard library.
959 let then = bx.build_sibling_block("then");
960 let catch = bx.build_sibling_block("catch");
962 let func = llvm::get_param(bx.llfn(), 0);
963 let data = llvm::get_param(bx.llfn(), 1);
964 let local_ptr = llvm::get_param(bx.llfn(), 2);
965 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
966 then.ret(cx.const_i32(0));
968 // Type indicator for the exception being thrown.
970 // The first value in this tuple is a pointer to the exception object
971 // being thrown. The second value is a "selector" indicating which of
972 // the landing pad clauses the exception's type had been matched to.
973 // rust_try ignores the selector.
974 let lpad_ty = cx.type_struct(&[cx.type_i8p(), cx.type_i32()], false);
975 let vals = catch.landing_pad(lpad_ty, bx.cx().eh_personality(), 1);
976 catch.add_clause(vals, bx.cx().const_null(cx.type_i8p()));
977 let ptr = catch.extract_value(vals, 0);
978 let ptr_align = bx.tcx().data_layout.pointer_align;
979 catch.store(ptr, catch.bitcast(local_ptr, cx.type_ptr_to(cx.type_i8p())), ptr_align);
980 catch.ret(cx.const_i32(1));
983 // Note that no invoke is used here because by definition this function
984 // can't panic (that's what it's catching).
985 let ret = bx.call(llfn, &[func, data, local_ptr], None);
986 let i32_align = bx.tcx().data_layout.i32_align;
987 bx.store(ret, dest, i32_align);
990 // Helper function to give a Block to a closure to codegen a shim function.
991 // This is currently primarily used for the `try` intrinsic functions above.
992 fn gen_fn<'ll, 'tcx>(
993 cx: &CodegenCx<'ll, 'tcx>,
995 inputs: Vec<Ty<'tcx>>,
997 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
999 let rust_fn_sig = ty::Binder::bind(cx.tcx.mk_fn_sig(
1003 hir::Unsafety::Unsafe,
1006 let llfn = declare::define_internal_fn(cx, name, rust_fn_sig);
1007 attributes::from_fn_attrs(cx, llfn, None);
1008 let bx = Builder::new_block(cx, llfn, "entry-block");
1013 // Helper function used to get a handle to the `__rust_try` function used to
1014 // catch exceptions.
1016 // This function is only generated once and is then cached.
1017 fn get_rust_try_fn<'ll, 'tcx>(
1018 cx: &CodegenCx<'ll, 'tcx>,
1019 codegen: &mut dyn FnMut(Builder<'_, 'll, 'tcx>),
1021 if let Some(llfn) = cx.rust_try_fn.get() {
1025 // Define the type up front for the signature of the rust_try function.
1027 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
1028 let fn_ty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
1032 hir::Unsafety::Unsafe,
1035 let output = tcx.types.i32;
1036 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, codegen);
1037 cx.rust_try_fn.set(Some(rust_try));
1041 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
1042 span_err!(a, b, E0511, "{}", c);
1045 fn generic_simd_intrinsic(
1046 bx: &Builder<'a, 'll, 'tcx>,
1048 callee_ty: Ty<'tcx>,
1049 args: &[OperandRef<'tcx, &'ll Value>],
1051 llret_ty: &'ll Type,
1053 ) -> Result<&'ll Value, ()> {
1054 // macros for error handling:
1055 macro_rules! emit_error {
1059 ($msg: tt, $($fmt: tt)*) => {
1060 span_invalid_monomorphization_error(
1062 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1067 macro_rules! return_error {
1070 emit_error!($($fmt)*);
1076 macro_rules! require {
1077 ($cond: expr, $($fmt: tt)*) => {
1079 return_error!($($fmt)*);
1084 macro_rules! require_simd {
1085 ($ty: expr, $position: expr) => {
1086 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1091 let sig = tcx.normalize_erasing_late_bound_regions(
1092 ty::ParamEnv::reveal_all(),
1093 &callee_ty.fn_sig(tcx),
1095 let arg_tys = sig.inputs();
1097 // every intrinsic takes a SIMD vector as its first argument
1098 require_simd!(arg_tys[0], "input");
1099 let in_ty = arg_tys[0];
1100 let in_elem = arg_tys[0].simd_type(tcx);
1101 let in_len = arg_tys[0].simd_size(tcx);
1103 let comparison = match name {
1104 "simd_eq" => Some(hir::BinOpKind::Eq),
1105 "simd_ne" => Some(hir::BinOpKind::Ne),
1106 "simd_lt" => Some(hir::BinOpKind::Lt),
1107 "simd_le" => Some(hir::BinOpKind::Le),
1108 "simd_gt" => Some(hir::BinOpKind::Gt),
1109 "simd_ge" => Some(hir::BinOpKind::Ge),
1113 if let Some(cmp_op) = comparison {
1114 require_simd!(ret_ty, "return");
1116 let out_len = ret_ty.simd_size(tcx);
1117 require!(in_len == out_len,
1118 "expected return type with length {} (same as input type `{}`), \
1119 found `{}` with length {}",
1122 require!(bx.cx().type_kind(bx.cx().element_type(llret_ty)) == TypeKind::Integer,
1123 "expected return type with integer elements, found `{}` with non-integer `{}`",
1125 ret_ty.simd_type(tcx));
1127 return Ok(compare_simd_types(bx,
1128 args[0].immediate(),
1129 args[1].immediate(),
1135 if name.starts_with("simd_shuffle") {
1136 let n: usize = name["simd_shuffle".len()..].parse().unwrap_or_else(|_|
1137 span_bug!(span, "bad `simd_shuffle` instruction only caught in codegen?"));
1139 require_simd!(ret_ty, "return");
1141 let out_len = ret_ty.simd_size(tcx);
1142 require!(out_len == n,
1143 "expected return type of length {}, found `{}` with length {}",
1144 n, ret_ty, out_len);
1145 require!(in_elem == ret_ty.simd_type(tcx),
1146 "expected return element type `{}` (element of input `{}`), \
1147 found `{}` with element type `{}`",
1149 ret_ty, ret_ty.simd_type(tcx));
1151 let total_len = in_len as u128 * 2;
1153 let vector = args[2].immediate();
1155 let indices: Option<Vec<_>> = (0..n)
1158 let val = bx.cx().const_get_elt(vector, i as u64);
1159 match bx.cx().const_to_opt_u128(val, true) {
1161 emit_error!("shuffle index #{} is not a constant", arg_idx);
1164 Some(idx) if idx >= total_len => {
1165 emit_error!("shuffle index #{} is out of bounds (limit {})",
1166 arg_idx, total_len);
1169 Some(idx) => Some(bx.cx().const_i32(idx as i32)),
1173 let indices = match indices {
1175 None => return Ok(bx.cx().const_null(llret_ty))
1178 return Ok(bx.shuffle_vector(args[0].immediate(),
1179 args[1].immediate(),
1180 bx.cx().const_vector(&indices)))
1183 if name == "simd_insert" {
1184 require!(in_elem == arg_tys[2],
1185 "expected inserted type `{}` (element of input `{}`), found `{}`",
1186 in_elem, in_ty, arg_tys[2]);
1187 return Ok(bx.insert_element(args[0].immediate(),
1188 args[2].immediate(),
1189 args[1].immediate()))
1191 if name == "simd_extract" {
1192 require!(ret_ty == in_elem,
1193 "expected return type `{}` (element of input `{}`), found `{}`",
1194 in_elem, in_ty, ret_ty);
1195 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1198 if name == "simd_select" {
1199 let m_elem_ty = in_elem;
1201 let v_len = arg_tys[1].simd_size(tcx);
1202 require!(m_len == v_len,
1203 "mismatched lengths: mask length `{}` != other vector length `{}`",
1206 match m_elem_ty.sty {
1208 _ => return_error!("mask element type is `{}`, expected `i_`", m_elem_ty)
1210 // truncate the mask to a vector of i1s
1211 let i1 = bx.cx().type_i1();
1212 let i1xn = bx.cx().type_vector(i1, m_len as u64);
1213 let m_i1s = bx.trunc(args[0].immediate(), i1xn);
1214 return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate()));
1217 fn simd_simple_float_intrinsic(
1219 in_elem: &::rustc::ty::TyS,
1220 in_ty: &::rustc::ty::TyS,
1222 bx: &Builder<'a, 'll, 'tcx>,
1224 args: &[OperandRef<'tcx, &'ll Value>],
1225 ) -> Result<&'ll Value, ()> {
1226 macro_rules! emit_error {
1230 ($msg: tt, $($fmt: tt)*) => {
1231 span_invalid_monomorphization_error(
1233 &format!(concat!("invalid monomorphization of `{}` intrinsic: ", $msg),
1237 macro_rules! return_error {
1240 emit_error!($($fmt)*);
1245 let ety = match in_elem.sty {
1246 ty::Float(f) if f.bit_width() == 32 => {
1247 if in_len < 2 || in_len > 16 {
1249 "unsupported floating-point vector `{}` with length `{}` \
1250 out-of-range [2, 16]",
1255 ty::Float(f) if f.bit_width() == 64 => {
1256 if in_len < 2 || in_len > 8 {
1257 return_error!("unsupported floating-point vector `{}` with length `{}` \
1258 out-of-range [2, 8]",
1264 return_error!("unsupported element type `{}` of floating-point vector `{}`",
1268 return_error!("`{}` is not a floating-point type", in_ty);
1272 let llvm_name = &format!("llvm.{0}.v{1}{2}", name, in_len, ety);
1273 let intrinsic = bx.cx().get_intrinsic(&llvm_name);
1274 let c = bx.call(intrinsic,
1275 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
1277 unsafe { llvm::LLVMRustSetHasUnsafeAlgebra(c) };
1283 return simd_simple_float_intrinsic("sqrt", in_elem, in_ty, in_len, bx, span, args);
1286 return simd_simple_float_intrinsic("sin", in_elem, in_ty, in_len, bx, span, args);
1289 return simd_simple_float_intrinsic("cos", in_elem, in_ty, in_len, bx, span, args);
1292 return simd_simple_float_intrinsic("fabs", in_elem, in_ty, in_len, bx, span, args);
1295 return simd_simple_float_intrinsic("floor", in_elem, in_ty, in_len, bx, span, args);
1298 return simd_simple_float_intrinsic("ceil", in_elem, in_ty, in_len, bx, span, args);
1301 return simd_simple_float_intrinsic("exp", in_elem, in_ty, in_len, bx, span, args);
1304 return simd_simple_float_intrinsic("exp2", in_elem, in_ty, in_len, bx, span, args);
1307 return simd_simple_float_intrinsic("log10", in_elem, in_ty, in_len, bx, span, args);
1310 return simd_simple_float_intrinsic("log2", in_elem, in_ty, in_len, bx, span, args);
1313 return simd_simple_float_intrinsic("log", in_elem, in_ty, in_len, bx, span, args);
1316 return simd_simple_float_intrinsic("powi", in_elem, in_ty, in_len, bx, span, args);
1319 return simd_simple_float_intrinsic("pow", in_elem, in_ty, in_len, bx, span, args);
1322 return simd_simple_float_intrinsic("fma", in_elem, in_ty, in_len, bx, span, args);
1324 _ => { /* fallthrough */ }
1328 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Function.h#L182
1329 // https://github.com/llvm-mirror/llvm/blob/master/include/llvm/IR/Intrinsics.h#L81
1330 fn llvm_vector_str(elem_ty: ty::Ty, vec_len: usize, no_pointers: usize) -> String {
1331 let p0s: String = "p0".repeat(no_pointers);
1333 ty::Int(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1334 ty::Uint(v) => format!("v{}{}i{}", vec_len, p0s, v.bit_width().unwrap()),
1335 ty::Float(v) => format!("v{}{}f{}", vec_len, p0s, v.bit_width()),
1336 _ => unreachable!(),
1340 fn llvm_vector_ty(cx: &CodegenCx<'ll, '_>, elem_ty: ty::Ty, vec_len: usize,
1341 mut no_pointers: usize) -> &'ll Type {
1342 // FIXME: use cx.layout_of(ty).llvm_type() ?
1343 let mut elem_ty = match elem_ty.sty {
1344 ty::Int(v) => cx.type_int_from_ty( v),
1345 ty::Uint(v) => cx.type_uint_from_ty( v),
1346 ty::Float(v) => cx.type_float_from_ty( v),
1347 _ => unreachable!(),
1349 while no_pointers > 0 {
1350 elem_ty = cx.type_ptr_to(elem_ty);
1353 cx.type_vector(elem_ty, vec_len as u64)
1357 if name == "simd_gather" {
1358 // simd_gather(values: <N x T>, pointers: <N x *_ T>,
1359 // mask: <N x i{M}>) -> <N x T>
1360 // * N: number of elements in the input vectors
1361 // * T: type of the element to load
1362 // * M: any integer width is supported, will be truncated to i1
1364 // All types must be simd vector types
1365 require_simd!(in_ty, "first");
1366 require_simd!(arg_tys[1], "second");
1367 require_simd!(arg_tys[2], "third");
1368 require_simd!(ret_ty, "return");
1370 // Of the same length:
1371 require!(in_len == arg_tys[1].simd_size(tcx),
1372 "expected {} argument with length {} (same as input type `{}`), \
1373 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1374 arg_tys[1].simd_size(tcx));
1375 require!(in_len == arg_tys[2].simd_size(tcx),
1376 "expected {} argument with length {} (same as input type `{}`), \
1377 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1378 arg_tys[2].simd_size(tcx));
1380 // The return type must match the first argument type
1381 require!(ret_ty == in_ty,
1382 "expected return type `{}`, found `{}`",
1385 // This counts how many pointers
1386 fn ptr_count(t: ty::Ty) -> usize {
1388 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1394 fn non_ptr(t: ty::Ty) -> ty::Ty {
1396 ty::RawPtr(p) => non_ptr(p.ty),
1401 // The second argument must be a simd vector with an element type that's a pointer
1402 // to the element type of the first argument
1403 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1404 ty::RawPtr(p) if p.ty == in_elem => (ptr_count(arg_tys[1].simd_type(tcx)),
1405 non_ptr(arg_tys[1].simd_type(tcx))),
1407 require!(false, "expected element type `{}` of second argument `{}` \
1408 to be a pointer to the element type `{}` of the first \
1409 argument `{}`, found `{}` != `*_ {}`",
1410 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1411 arg_tys[1].simd_type(tcx).sty, in_elem);
1415 assert!(pointer_count > 0);
1416 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1417 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1419 // The element type of the third argument must be a signed integer type of any width:
1420 match arg_tys[2].simd_type(tcx).sty {
1423 require!(false, "expected element type `{}` of third argument `{}` \
1424 to be a signed integer type",
1425 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1429 // Alignment of T, must be a constant integer value:
1430 let alignment_ty = bx.cx().type_i32();
1431 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1433 // Truncate the mask vector to a vector of i1s:
1434 let (mask, mask_ty) = {
1435 let i1 = bx.cx().type_i1();
1436 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1437 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1440 // Type of the vector of pointers:
1441 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1442 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1444 // Type of the vector of elements:
1445 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1446 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1448 let llvm_intrinsic = format!("llvm.masked.gather.{}.{}",
1449 llvm_elem_vec_str, llvm_pointer_vec_str);
1450 let f = declare::declare_cfn(bx.cx(), &llvm_intrinsic,
1451 bx.cx().type_func(&[
1452 llvm_pointer_vec_ty,
1455 llvm_elem_vec_ty], llvm_elem_vec_ty));
1456 llvm::SetUnnamedAddr(f, false);
1457 let v = bx.call(f, &[args[1].immediate(), alignment, mask, args[0].immediate()],
1462 if name == "simd_scatter" {
1463 // simd_scatter(values: <N x T>, pointers: <N x *mut T>,
1464 // mask: <N x i{M}>) -> ()
1465 // * N: number of elements in the input vectors
1466 // * T: type of the element to load
1467 // * M: any integer width is supported, will be truncated to i1
1469 // All types must be simd vector types
1470 require_simd!(in_ty, "first");
1471 require_simd!(arg_tys[1], "second");
1472 require_simd!(arg_tys[2], "third");
1474 // Of the same length:
1475 require!(in_len == arg_tys[1].simd_size(tcx),
1476 "expected {} argument with length {} (same as input type `{}`), \
1477 found `{}` with length {}", "second", in_len, in_ty, arg_tys[1],
1478 arg_tys[1].simd_size(tcx));
1479 require!(in_len == arg_tys[2].simd_size(tcx),
1480 "expected {} argument with length {} (same as input type `{}`), \
1481 found `{}` with length {}", "third", in_len, in_ty, arg_tys[2],
1482 arg_tys[2].simd_size(tcx));
1484 // This counts how many pointers
1485 fn ptr_count(t: ty::Ty) -> usize {
1487 ty::RawPtr(p) => 1 + ptr_count(p.ty),
1493 fn non_ptr(t: ty::Ty) -> ty::Ty {
1495 ty::RawPtr(p) => non_ptr(p.ty),
1500 // The second argument must be a simd vector with an element type that's a pointer
1501 // to the element type of the first argument
1502 let (pointer_count, underlying_ty) = match arg_tys[1].simd_type(tcx).sty {
1503 ty::RawPtr(p) if p.ty == in_elem && p.mutbl == hir::MutMutable
1504 => (ptr_count(arg_tys[1].simd_type(tcx)),
1505 non_ptr(arg_tys[1].simd_type(tcx))),
1507 require!(false, "expected element type `{}` of second argument `{}` \
1508 to be a pointer to the element type `{}` of the first \
1509 argument `{}`, found `{}` != `*mut {}`",
1510 arg_tys[1].simd_type(tcx).sty, arg_tys[1], in_elem, in_ty,
1511 arg_tys[1].simd_type(tcx).sty, in_elem);
1515 assert!(pointer_count > 0);
1516 assert_eq!(pointer_count - 1, ptr_count(arg_tys[0].simd_type(tcx)));
1517 assert_eq!(underlying_ty, non_ptr(arg_tys[0].simd_type(tcx)));
1519 // The element type of the third argument must be a signed integer type of any width:
1520 match arg_tys[2].simd_type(tcx).sty {
1523 require!(false, "expected element type `{}` of third argument `{}` \
1524 to be a signed integer type",
1525 arg_tys[2].simd_type(tcx).sty, arg_tys[2]);
1529 // Alignment of T, must be a constant integer value:
1530 let alignment_ty = bx.cx().type_i32();
1531 let alignment = bx.cx().const_i32(bx.cx().align_of(in_elem).abi() as i32);
1533 // Truncate the mask vector to a vector of i1s:
1534 let (mask, mask_ty) = {
1535 let i1 = bx.cx().type_i1();
1536 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1537 (bx.trunc(args[2].immediate(), i1xn), i1xn)
1540 let ret_t = bx.cx().type_void();
1542 // Type of the vector of pointers:
1543 let llvm_pointer_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count);
1544 let llvm_pointer_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count);
1546 // Type of the vector of elements:
1547 let llvm_elem_vec_ty = llvm_vector_ty(bx.cx(), underlying_ty, in_len, pointer_count - 1);
1548 let llvm_elem_vec_str = llvm_vector_str(underlying_ty, in_len, pointer_count - 1);
1550 let llvm_intrinsic = format!("llvm.masked.scatter.{}.{}",
1551 llvm_elem_vec_str, llvm_pointer_vec_str);
1552 let f = declare::declare_cfn(bx.cx(), &llvm_intrinsic,
1553 bx.cx().type_func(&[llvm_elem_vec_ty,
1554 llvm_pointer_vec_ty,
1557 llvm::SetUnnamedAddr(f, false);
1558 let v = bx.call(f, &[args[0].immediate(), args[1].immediate(), alignment, mask],
1563 macro_rules! arith_red {
1564 ($name:tt : $integer_reduce:ident, $float_reduce:ident, $ordered:expr) => {
1566 require!(ret_ty == in_elem,
1567 "expected return type `{}` (element of input `{}`), found `{}`",
1568 in_elem, in_ty, ret_ty);
1569 return match in_elem.sty {
1570 ty::Int(_) | ty::Uint(_) => {
1571 let r = bx.$integer_reduce(args[0].immediate());
1573 // if overflow occurs, the result is the
1574 // mathematical result modulo 2^n:
1575 if name.contains("mul") {
1576 Ok(bx.mul(args[1].immediate(), r))
1578 Ok(bx.add(args[1].immediate(), r))
1581 Ok(bx.$integer_reduce(args[0].immediate()))
1585 // ordered arithmetic reductions take an accumulator
1586 let acc = if $ordered {
1587 let acc = args[1].immediate();
1588 // FIXME: https://bugs.llvm.org/show_bug.cgi?id=36734
1589 // * if the accumulator of the fadd isn't 0, incorrect
1590 // code is generated
1591 // * if the accumulator of the fmul isn't 1, incorrect
1592 // code is generated
1593 match bx.cx().const_get_real(acc) {
1594 None => return_error!("accumulator of {} is not a constant", $name),
1595 Some((v, loses_info)) => {
1596 if $name.contains("mul") && v != 1.0_f64 {
1597 return_error!("accumulator of {} is not 1.0", $name);
1598 } else if $name.contains("add") && v != 0.0_f64 {
1599 return_error!("accumulator of {} is not 0.0", $name);
1600 } else if loses_info {
1601 return_error!("accumulator of {} loses information", $name);
1607 // unordered arithmetic reductions do not:
1608 match f.bit_width() {
1609 32 => bx.cx().const_undef(bx.cx().type_f32()),
1610 64 => bx.cx().const_undef(bx.cx().type_f64()),
1613 unsupported {} from `{}` with element `{}` of size `{}` to `{}`"#,
1614 $name, in_ty, in_elem, v, ret_ty
1619 Ok(bx.$float_reduce(acc, args[0].immediate()))
1623 "unsupported {} from `{}` with element `{}` to `{}`",
1624 $name, in_ty, in_elem, ret_ty
1632 arith_red!("simd_reduce_add_ordered": vector_reduce_add, vector_reduce_fadd_fast, true);
1633 arith_red!("simd_reduce_mul_ordered": vector_reduce_mul, vector_reduce_fmul_fast, true);
1634 arith_red!("simd_reduce_add_unordered": vector_reduce_add, vector_reduce_fadd_fast, false);
1635 arith_red!("simd_reduce_mul_unordered": vector_reduce_mul, vector_reduce_fmul_fast, false);
1637 macro_rules! minmax_red {
1638 ($name:tt: $int_red:ident, $float_red:ident) => {
1640 require!(ret_ty == in_elem,
1641 "expected return type `{}` (element of input `{}`), found `{}`",
1642 in_elem, in_ty, ret_ty);
1643 return match in_elem.sty {
1645 Ok(bx.$int_red(args[0].immediate(), true))
1648 Ok(bx.$int_red(args[0].immediate(), false))
1651 Ok(bx.$float_red(args[0].immediate()))
1654 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1655 $name, in_ty, in_elem, ret_ty)
1663 minmax_red!("simd_reduce_min": vector_reduce_min, vector_reduce_fmin);
1664 minmax_red!("simd_reduce_max": vector_reduce_max, vector_reduce_fmax);
1666 minmax_red!("simd_reduce_min_nanless": vector_reduce_min, vector_reduce_fmin_fast);
1667 minmax_red!("simd_reduce_max_nanless": vector_reduce_max, vector_reduce_fmax_fast);
1669 macro_rules! bitwise_red {
1670 ($name:tt : $red:ident, $boolean:expr) => {
1672 let input = if !$boolean {
1673 require!(ret_ty == in_elem,
1674 "expected return type `{}` (element of input `{}`), found `{}`",
1675 in_elem, in_ty, ret_ty);
1679 ty::Int(_) | ty::Uint(_) => {},
1681 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1682 $name, in_ty, in_elem, ret_ty)
1686 // boolean reductions operate on vectors of i1s:
1687 let i1 = bx.cx().type_i1();
1688 let i1xn = bx.cx().type_vector(i1, in_len as u64);
1689 bx.trunc(args[0].immediate(), i1xn)
1691 return match in_elem.sty {
1692 ty::Int(_) | ty::Uint(_) => {
1693 let r = bx.$red(input);
1698 bx.zext(r, bx.cx().type_bool())
1703 return_error!("unsupported {} from `{}` with element `{}` to `{}`",
1704 $name, in_ty, in_elem, ret_ty)
1711 bitwise_red!("simd_reduce_and": vector_reduce_and, false);
1712 bitwise_red!("simd_reduce_or": vector_reduce_or, false);
1713 bitwise_red!("simd_reduce_xor": vector_reduce_xor, false);
1714 bitwise_red!("simd_reduce_all": vector_reduce_and, true);
1715 bitwise_red!("simd_reduce_any": vector_reduce_or, true);
1717 if name == "simd_cast" {
1718 require_simd!(ret_ty, "return");
1719 let out_len = ret_ty.simd_size(tcx);
1720 require!(in_len == out_len,
1721 "expected return type with length {} (same as input type `{}`), \
1722 found `{}` with length {}",
1725 // casting cares about nominal type, not just structural type
1726 let out_elem = ret_ty.simd_type(tcx);
1728 if in_elem == out_elem { return Ok(args[0].immediate()); }
1730 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1732 let (in_style, in_width) = match in_elem.sty {
1733 // vectors of pointer-sized integers should've been
1734 // disallowed before here, so this unwrap is safe.
1735 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1736 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1737 ty::Float(f) => (Style::Float, f.bit_width()),
1738 _ => (Style::Unsupported, 0)
1740 let (out_style, out_width) = match out_elem.sty {
1741 ty::Int(i) => (Style::Int(true), i.bit_width().unwrap()),
1742 ty::Uint(u) => (Style::Int(false), u.bit_width().unwrap()),
1743 ty::Float(f) => (Style::Float, f.bit_width()),
1744 _ => (Style::Unsupported, 0)
1747 match (in_style, out_style) {
1748 (Style::Int(in_is_signed), Style::Int(_)) => {
1749 return Ok(match in_width.cmp(&out_width) {
1750 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1751 Ordering::Equal => args[0].immediate(),
1752 Ordering::Less => if in_is_signed {
1753 bx.sext(args[0].immediate(), llret_ty)
1755 bx.zext(args[0].immediate(), llret_ty)
1759 (Style::Int(in_is_signed), Style::Float) => {
1760 return Ok(if in_is_signed {
1761 bx.sitofp(args[0].immediate(), llret_ty)
1763 bx.uitofp(args[0].immediate(), llret_ty)
1766 (Style::Float, Style::Int(out_is_signed)) => {
1767 return Ok(if out_is_signed {
1768 bx.fptosi(args[0].immediate(), llret_ty)
1770 bx.fptoui(args[0].immediate(), llret_ty)
1773 (Style::Float, Style::Float) => {
1774 return Ok(match in_width.cmp(&out_width) {
1775 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1776 Ordering::Equal => args[0].immediate(),
1777 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1780 _ => {/* Unsupported. Fallthrough. */}
1783 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1787 macro_rules! arith {
1788 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1789 $(if name == stringify!($name) {
1791 $($(ty::$p(_))|* => {
1792 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1797 "unsupported operation on `{}` with element `{}`",
1804 simd_add: Uint, Int => add, Float => fadd;
1805 simd_sub: Uint, Int => sub, Float => fsub;
1806 simd_mul: Uint, Int => mul, Float => fmul;
1807 simd_div: Uint => udiv, Int => sdiv, Float => fdiv;
1808 simd_rem: Uint => urem, Int => srem, Float => frem;
1809 simd_shl: Uint, Int => shl;
1810 simd_shr: Uint => lshr, Int => ashr;
1811 simd_and: Uint, Int => and;
1812 simd_or: Uint, Int => or;
1813 simd_xor: Uint, Int => xor;
1814 simd_fmax: Float => maxnum;
1815 simd_fmin: Float => minnum;
1817 span_bug!(span, "unknown SIMD intrinsic");
1820 // Returns the width of an int Ty, and if it's signed or not
1821 // Returns None if the type is not an integer
1822 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1824 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1826 ty::Int(t) => Some((match t {
1827 ast::IntTy::Isize => cx.tcx.sess.target.isize_ty.bit_width().unwrap() as u64,
1828 ast::IntTy::I8 => 8,
1829 ast::IntTy::I16 => 16,
1830 ast::IntTy::I32 => 32,
1831 ast::IntTy::I64 => 64,
1832 ast::IntTy::I128 => 128,
1834 ty::Uint(t) => Some((match t {
1835 ast::UintTy::Usize => cx.tcx.sess.target.usize_ty.bit_width().unwrap() as u64,
1836 ast::UintTy::U8 => 8,
1837 ast::UintTy::U16 => 16,
1838 ast::UintTy::U32 => 32,
1839 ast::UintTy::U64 => 64,
1840 ast::UintTy::U128 => 128,
1846 // Returns the width of a float TypeVariant
1847 // Returns None if the type is not a float
1848 fn float_type_width<'tcx>(sty: &ty::TyKind<'tcx>) -> Option<u64> {
1850 ty::Float(t) => Some(t.bit_width() as u64),