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)]
13 use intrinsics::{self, Intrinsic};
16 use abi::{Abi, FnType, PassMode};
17 use mir::place::PlaceRef;
18 use mir::operand::{OperandRef, OperandValue};
24 use type_of::LayoutLlvmExt;
25 use rustc::ty::{self, Ty};
26 use rustc::ty::layout::{HasDataLayout, LayoutOf};
29 use syntax::symbol::Symbol;
32 use rustc::session::Session;
35 use std::cmp::Ordering;
38 fn get_simple_intrinsic(cx: &CodegenCx, name: &str) -> Option<ValueRef> {
39 let llvm_name = match name {
40 "sqrtf32" => "llvm.sqrt.f32",
41 "sqrtf64" => "llvm.sqrt.f64",
42 "powif32" => "llvm.powi.f32",
43 "powif64" => "llvm.powi.f64",
44 "sinf32" => "llvm.sin.f32",
45 "sinf64" => "llvm.sin.f64",
46 "cosf32" => "llvm.cos.f32",
47 "cosf64" => "llvm.cos.f64",
48 "powf32" => "llvm.pow.f32",
49 "powf64" => "llvm.pow.f64",
50 "expf32" => "llvm.exp.f32",
51 "expf64" => "llvm.exp.f64",
52 "exp2f32" => "llvm.exp2.f32",
53 "exp2f64" => "llvm.exp2.f64",
54 "logf32" => "llvm.log.f32",
55 "logf64" => "llvm.log.f64",
56 "log10f32" => "llvm.log10.f32",
57 "log10f64" => "llvm.log10.f64",
58 "log2f32" => "llvm.log2.f32",
59 "log2f64" => "llvm.log2.f64",
60 "fmaf32" => "llvm.fma.f32",
61 "fmaf64" => "llvm.fma.f64",
62 "fabsf32" => "llvm.fabs.f32",
63 "fabsf64" => "llvm.fabs.f64",
64 "copysignf32" => "llvm.copysign.f32",
65 "copysignf64" => "llvm.copysign.f64",
66 "floorf32" => "llvm.floor.f32",
67 "floorf64" => "llvm.floor.f64",
68 "ceilf32" => "llvm.ceil.f32",
69 "ceilf64" => "llvm.ceil.f64",
70 "truncf32" => "llvm.trunc.f32",
71 "truncf64" => "llvm.trunc.f64",
72 "rintf32" => "llvm.rint.f32",
73 "rintf64" => "llvm.rint.f64",
74 "nearbyintf32" => "llvm.nearbyint.f32",
75 "nearbyintf64" => "llvm.nearbyint.f64",
76 "roundf32" => "llvm.round.f32",
77 "roundf64" => "llvm.round.f64",
78 "assume" => "llvm.assume",
79 "abort" => "llvm.trap",
82 Some(cx.get_intrinsic(&llvm_name))
85 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
86 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
87 /// add them to librustc_trans/trans/context.rs
88 pub fn trans_intrinsic_call<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
91 args: &[OperandRef<'tcx>],
97 let (def_id, substs) = match callee_ty.sty {
98 ty::TyFnDef(def_id, substs) => (def_id, substs),
99 _ => bug!("expected fn item type, found {}", callee_ty)
102 let sig = callee_ty.fn_sig(tcx);
103 let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
104 let arg_tys = sig.inputs();
105 let ret_ty = sig.output();
106 let name = &*tcx.item_name(def_id);
108 let llret_ty = cx.layout_of(ret_ty).llvm_type(cx);
109 let result = PlaceRef::new_sized(llresult, fn_ty.ret.layout, fn_ty.ret.layout.align);
111 let simple = get_simple_intrinsic(cx, name);
112 let llval = match name {
113 _ if simple.is_some() => {
114 bx.call(simple.unwrap(),
115 &args.iter().map(|arg| arg.immediate()).collect::<Vec<_>>(),
122 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
123 bx.call(expect, &[args[0].immediate(), C_bool(cx, true)], None)
126 let expect = cx.get_intrinsic(&("llvm.expect.i1"));
127 bx.call(expect, &[args[0].immediate(), C_bool(cx, false)], None)
130 try_intrinsic(bx, cx,
138 let llfn = cx.get_intrinsic(&("llvm.debugtrap"));
139 bx.call(llfn, &[], None)
142 let tp_ty = substs.type_at(0);
143 C_usize(cx, cx.size_of(tp_ty).bytes())
146 let tp_ty = substs.type_at(0);
147 if let OperandValue::Pair(_, meta) = args[0].val {
149 glue::size_and_align_of_dst(bx, tp_ty, meta);
152 C_usize(cx, cx.size_of(tp_ty).bytes())
156 let tp_ty = substs.type_at(0);
157 C_usize(cx, cx.align_of(tp_ty).abi())
159 "min_align_of_val" => {
160 let tp_ty = substs.type_at(0);
161 if let OperandValue::Pair(_, meta) = args[0].val {
163 glue::size_and_align_of_dst(bx, tp_ty, meta);
166 C_usize(cx, cx.align_of(tp_ty).abi())
170 let tp_ty = substs.type_at(0);
171 C_usize(cx, cx.align_of(tp_ty).pref())
174 let tp_ty = substs.type_at(0);
175 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
176 C_str_slice(cx, ty_name)
179 C_u64(cx, cx.tcx.type_id_hash(substs.type_at(0)))
182 let ty = substs.type_at(0);
183 if !cx.layout_of(ty).is_zst() {
184 // Just zero out the stack slot.
185 // If we store a zero constant, LLVM will drown in vreg allocation for large data
186 // structures, and the generated code will be awful. (A telltale sign of this is
187 // large quantities of `mov [byte ptr foo],0` in the generated code.)
188 memset_intrinsic(bx, false, ty, llresult, C_u8(cx, 0), C_usize(cx, 1));
192 // Effectively no-ops
197 let tp_ty = substs.type_at(0);
199 C_bool(cx, bx.cx.type_needs_drop(tp_ty))
202 let ptr = args[0].immediate();
203 let offset = args[1].immediate();
204 bx.inbounds_gep(ptr, &[offset])
207 let ptr = args[0].immediate();
208 let offset = args[1].immediate();
209 bx.gep(ptr, &[offset])
212 "copy_nonoverlapping" => {
213 copy_intrinsic(bx, false, false, substs.type_at(0),
214 args[1].immediate(), args[0].immediate(), args[2].immediate())
217 copy_intrinsic(bx, true, false, substs.type_at(0),
218 args[1].immediate(), args[0].immediate(), args[2].immediate())
221 memset_intrinsic(bx, false, substs.type_at(0),
222 args[0].immediate(), args[1].immediate(), args[2].immediate())
225 "volatile_copy_nonoverlapping_memory" => {
226 copy_intrinsic(bx, false, true, substs.type_at(0),
227 args[0].immediate(), args[1].immediate(), args[2].immediate())
229 "volatile_copy_memory" => {
230 copy_intrinsic(bx, true, true, substs.type_at(0),
231 args[0].immediate(), args[1].immediate(), args[2].immediate())
233 "volatile_set_memory" => {
234 memset_intrinsic(bx, true, substs.type_at(0),
235 args[0].immediate(), args[1].immediate(), args[2].immediate())
238 let tp_ty = substs.type_at(0);
239 let mut ptr = args[0].immediate();
240 if let PassMode::Cast(ty) = fn_ty.ret.mode {
241 ptr = bx.pointercast(ptr, ty.llvm_type(cx).ptr_to());
243 let load = bx.volatile_load(ptr);
245 llvm::LLVMSetAlignment(load, cx.align_of(tp_ty).abi() as u32);
247 to_immediate(bx, load, cx.layout_of(tp_ty))
249 "volatile_store" => {
250 let tp_ty = substs.type_at(0);
251 let dst = args[0].deref(bx.cx);
252 if let OperandValue::Pair(a, b) = args[1].val {
253 bx.volatile_store(a, dst.project_field(bx, 0).llval);
254 bx.volatile_store(b, dst.project_field(bx, 1).llval);
256 let val = if let OperandValue::Ref(ptr, align) = args[1].val {
259 if dst.layout.is_zst() {
262 from_immediate(bx, args[1].immediate())
264 let ptr = bx.pointercast(dst.llval, val_ty(val).ptr_to());
265 let store = bx.volatile_store(val, ptr);
267 llvm::LLVMSetAlignment(store, cx.align_of(tp_ty).abi() as u32);
272 "prefetch_read_data" | "prefetch_write_data" |
273 "prefetch_read_instruction" | "prefetch_write_instruction" => {
274 let expect = cx.get_intrinsic(&("llvm.prefetch"));
275 let (rw, cache_type) = match name {
276 "prefetch_read_data" => (0, 1),
277 "prefetch_write_data" => (1, 1),
278 "prefetch_read_instruction" => (0, 0),
279 "prefetch_write_instruction" => (1, 0),
286 C_i32(cx, cache_type)
289 "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "ctpop" | "bswap" |
290 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" |
291 "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
292 "unchecked_div" | "unchecked_rem" | "unchecked_shl" | "unchecked_shr" => {
294 match int_type_width_signed(ty, cx) {
295 Some((width, signed)) =>
298 let y = C_bool(bx.cx, false);
299 let llfn = cx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
300 bx.call(llfn, &[args[0].immediate(), y], None)
302 "ctlz_nonzero" | "cttz_nonzero" => {
303 let y = C_bool(bx.cx, true);
304 let llvm_name = &format!("llvm.{}.i{}", &name[..4], width);
305 let llfn = cx.get_intrinsic(llvm_name);
306 bx.call(llfn, &[args[0].immediate(), y], None)
308 "ctpop" => bx.call(cx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
309 &[args[0].immediate()], None),
312 args[0].immediate() // byte swap a u8/i8 is just a no-op
314 bx.call(cx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
315 &[args[0].immediate()], None)
318 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
319 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
320 if signed { 's' } else { 'u' },
322 let llfn = bx.cx.get_intrinsic(&intrinsic);
324 // Convert `i1` to a `bool`, and write it to the out parameter
325 let pair = bx.call(llfn, &[
329 let val = bx.extract_value(pair, 0);
330 let overflow = bx.zext(bx.extract_value(pair, 1), Type::bool(cx));
332 let dest = result.project_field(bx, 0);
333 bx.store(val, dest.llval, dest.align);
334 let dest = result.project_field(bx, 1);
335 bx.store(overflow, dest.llval, dest.align);
339 "overflowing_add" => bx.add(args[0].immediate(), args[1].immediate()),
340 "overflowing_sub" => bx.sub(args[0].immediate(), args[1].immediate()),
341 "overflowing_mul" => bx.mul(args[0].immediate(), args[1].immediate()),
344 bx.sdiv(args[0].immediate(), args[1].immediate())
346 bx.udiv(args[0].immediate(), args[1].immediate())
350 bx.srem(args[0].immediate(), args[1].immediate())
352 bx.urem(args[0].immediate(), args[1].immediate())
354 "unchecked_shl" => bx.shl(args[0].immediate(), args[1].immediate()),
357 bx.ashr(args[0].immediate(), args[1].immediate())
359 bx.lshr(args[0].immediate(), args[1].immediate())
364 span_invalid_monomorphization_error(
366 &format!("invalid monomorphization of `{}` intrinsic: \
367 expected basic integer type, found `{}`", name, ty));
373 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
374 let sty = &arg_tys[0].sty;
375 match float_type_width(sty) {
378 "fadd_fast" => bx.fadd_fast(args[0].immediate(), args[1].immediate()),
379 "fsub_fast" => bx.fsub_fast(args[0].immediate(), args[1].immediate()),
380 "fmul_fast" => bx.fmul_fast(args[0].immediate(), args[1].immediate()),
381 "fdiv_fast" => bx.fdiv_fast(args[0].immediate(), args[1].immediate()),
382 "frem_fast" => bx.frem_fast(args[0].immediate(), args[1].immediate()),
386 span_invalid_monomorphization_error(
388 &format!("invalid monomorphization of `{}` intrinsic: \
389 expected basic float type, found `{}`", name, sty));
396 "discriminant_value" => {
397 args[0].deref(bx.cx).trans_get_discr(bx, ret_ty)
402 let ptr_val = bx.ptrtoint(args[0].immediate(), bx.cx.isize_ty);
404 let align = args[1].immediate();
405 let offset = bx.urem(ptr_val, align);
406 let zero = C_null(bx.cx.isize_ty);
408 let is_zero = bx.icmp(llvm::IntPredicate::IntEQ, offset, zero);
409 // `if offset == 0 { 0 } else { align - offset }`
410 bx.select(is_zero, zero, bx.sub(align, offset))
412 name if name.starts_with("simd_") => {
413 match generic_simd_intrinsic(bx, name,
422 // This requires that atomic intrinsics follow a specific naming pattern:
423 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
424 name if name.starts_with("atomic_") => {
425 use llvm::AtomicOrdering::*;
427 let split: Vec<&str> = name.split('_').collect();
429 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
430 let (order, failorder) = match split.len() {
431 2 => (SequentiallyConsistent, SequentiallyConsistent),
432 3 => match split[2] {
433 "unordered" => (Unordered, Unordered),
434 "relaxed" => (Monotonic, Monotonic),
435 "acq" => (Acquire, Acquire),
436 "rel" => (Release, Monotonic),
437 "acqrel" => (AcquireRelease, Acquire),
438 "failrelaxed" if is_cxchg =>
439 (SequentiallyConsistent, Monotonic),
440 "failacq" if is_cxchg =>
441 (SequentiallyConsistent, Acquire),
442 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
444 4 => match (split[2], split[3]) {
445 ("acq", "failrelaxed") if is_cxchg =>
446 (Acquire, Monotonic),
447 ("acqrel", "failrelaxed") if is_cxchg =>
448 (AcquireRelease, Monotonic),
449 _ => cx.sess().fatal("unknown ordering in atomic intrinsic")
451 _ => cx.sess().fatal("Atomic intrinsic not in correct format"),
454 let invalid_monomorphization = |ty| {
455 span_invalid_monomorphization_error(tcx.sess, span,
456 &format!("invalid monomorphization of `{}` intrinsic: \
457 expected basic integer type, found `{}`", name, ty));
461 "cxchg" | "cxchgweak" => {
462 let ty = substs.type_at(0);
463 if int_type_width_signed(ty, cx).is_some() {
464 let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False };
465 let pair = bx.atomic_cmpxchg(
472 let val = bx.extract_value(pair, 0);
473 let success = bx.zext(bx.extract_value(pair, 1), Type::bool(bx.cx));
475 let dest = result.project_field(bx, 0);
476 bx.store(val, dest.llval, dest.align);
477 let dest = result.project_field(bx, 1);
478 bx.store(success, dest.llval, dest.align);
481 return invalid_monomorphization(ty);
486 let ty = substs.type_at(0);
487 if int_type_width_signed(ty, cx).is_some() {
488 let align = cx.align_of(ty);
489 bx.atomic_load(args[0].immediate(), order, align)
491 return invalid_monomorphization(ty);
496 let ty = substs.type_at(0);
497 if int_type_width_signed(ty, cx).is_some() {
498 let align = cx.align_of(ty);
499 bx.atomic_store(args[1].immediate(), args[0].immediate(), order, align);
502 return invalid_monomorphization(ty);
507 bx.atomic_fence(order, llvm::SynchronizationScope::CrossThread);
511 "singlethreadfence" => {
512 bx.atomic_fence(order, llvm::SynchronizationScope::SingleThread);
516 // These are all AtomicRMW ops
518 let atom_op = match op {
519 "xchg" => llvm::AtomicXchg,
520 "xadd" => llvm::AtomicAdd,
521 "xsub" => llvm::AtomicSub,
522 "and" => llvm::AtomicAnd,
523 "nand" => llvm::AtomicNand,
524 "or" => llvm::AtomicOr,
525 "xor" => llvm::AtomicXor,
526 "max" => llvm::AtomicMax,
527 "min" => llvm::AtomicMin,
528 "umax" => llvm::AtomicUMax,
529 "umin" => llvm::AtomicUMin,
530 _ => cx.sess().fatal("unknown atomic operation")
533 let ty = substs.type_at(0);
534 if int_type_width_signed(ty, cx).is_some() {
535 bx.atomic_rmw(atom_op, args[0].immediate(), args[1].immediate(), order)
537 return invalid_monomorphization(ty);
543 "nontemporal_store" => {
544 let tp_ty = substs.type_at(0);
545 let dst = args[0].deref(bx.cx);
546 let val = if let OperandValue::Ref(ptr, align) = args[1].val {
549 from_immediate(bx, args[1].immediate())
551 let ptr = bx.pointercast(dst.llval, val_ty(val).ptr_to());
552 let store = bx.nontemporal_store(val, ptr);
554 llvm::LLVMSetAlignment(store, cx.align_of(tp_ty).abi() as u32);
560 let intr = match Intrinsic::find(&name) {
562 None => bug!("unknown intrinsic '{}'", name),
564 fn one<T>(x: Vec<T>) -> T {
565 assert_eq!(x.len(), 1);
566 x.into_iter().next().unwrap()
568 fn ty_to_type(cx: &CodegenCx, t: &intrinsics::Type) -> Vec<Type> {
569 use intrinsics::Type::*;
571 Void => vec![Type::void(cx)],
572 Integer(_signed, _width, llvm_width) => {
573 vec![Type::ix(cx, llvm_width as u64)]
577 32 => vec![Type::f32(cx)],
578 64 => vec![Type::f64(cx)],
582 Pointer(ref t, ref llvm_elem, _const) => {
583 let t = llvm_elem.as_ref().unwrap_or(t);
584 let elem = one(ty_to_type(cx, t));
587 Vector(ref t, ref llvm_elem, length) => {
588 let t = llvm_elem.as_ref().unwrap_or(t);
589 let elem = one(ty_to_type(cx, t));
590 vec![Type::vector(&elem, length as u64)]
592 Aggregate(false, ref contents) => {
593 let elems = contents.iter()
594 .map(|t| one(ty_to_type(cx, t)))
595 .collect::<Vec<_>>();
596 vec![Type::struct_(cx, &elems, false)]
598 Aggregate(true, ref contents) => {
600 .flat_map(|t| ty_to_type(cx, t))
606 // This allows an argument list like `foo, (bar, baz),
607 // qux` to be converted into `foo, bar, baz, qux`, integer
608 // arguments to be truncated as needed and pointers to be
610 fn modify_as_needed<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
611 t: &intrinsics::Type,
612 arg: &OperandRef<'tcx>)
616 intrinsics::Type::Aggregate(true, ref contents) => {
617 // We found a tuple that needs squishing! So
618 // run over the tuple and load each field.
620 // This assumes the type is "simple", i.e. no
621 // destructors, and the contents are SIMD
623 assert!(!bx.cx.type_needs_drop(arg.layout.ty));
624 let (ptr, align) = match arg.val {
625 OperandValue::Ref(ptr, align) => (ptr, align),
628 let arg = PlaceRef::new_sized(ptr, arg.layout, align);
629 (0..contents.len()).map(|i| {
630 arg.project_field(bx, i).load(bx).immediate()
633 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
634 let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
635 vec![bx.pointercast(arg.immediate(), llvm_elem.ptr_to())]
637 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
638 let llvm_elem = one(ty_to_type(bx.cx, llvm_elem));
639 vec![bx.bitcast(arg.immediate(), Type::vector(&llvm_elem, length as u64))]
641 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
642 // the LLVM intrinsic uses a smaller integer
643 // size than the C intrinsic's signature, so
644 // we have to trim it down here.
645 vec![bx.trunc(arg.immediate(), Type::ix(bx.cx, llvm_width as u64))]
647 _ => vec![arg.immediate()],
652 let inputs = intr.inputs.iter()
653 .flat_map(|t| ty_to_type(cx, t))
654 .collect::<Vec<_>>();
656 let outputs = one(ty_to_type(cx, &intr.output));
658 let llargs: Vec<_> = intr.inputs.iter().zip(args).flat_map(|(t, arg)| {
659 modify_as_needed(bx, t, arg)
661 assert_eq!(inputs.len(), llargs.len());
663 let val = match intr.definition {
664 intrinsics::IntrinsicDef::Named(name) => {
665 let f = declare::declare_cfn(cx,
667 Type::func(&inputs, &outputs));
668 bx.call(f, &llargs, None)
673 intrinsics::Type::Aggregate(flatten, ref elems) => {
674 // the output is a tuple so we need to munge it properly
677 for i in 0..elems.len() {
678 let dest = result.project_field(bx, i);
679 let val = bx.extract_value(val, i as u64);
680 bx.store(val, dest.llval, dest.align);
689 if !fn_ty.ret.is_ignore() {
690 if let PassMode::Cast(ty) = fn_ty.ret.mode {
691 let ptr = bx.pointercast(result.llval, ty.llvm_type(cx).ptr_to());
692 bx.store(llval, ptr, result.align);
694 OperandRef::from_immediate_or_packed_pair(bx, llval, result.layout)
695 .val.store(bx, result);
700 fn copy_intrinsic<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
709 let (size, align) = cx.size_and_align_of(ty);
710 let size = C_usize(cx, size.bytes());
711 let align = C_i32(cx, align.abi() as i32);
713 let operation = if allow_overlap {
719 let name = format!("llvm.{}.p0i8.p0i8.i{}", operation,
720 cx.data_layout().pointer_size.bits());
722 let dst_ptr = bx.pointercast(dst, Type::i8p(cx));
723 let src_ptr = bx.pointercast(src, Type::i8p(cx));
724 let llfn = cx.get_intrinsic(&name);
731 C_bool(cx, volatile)],
735 fn memset_intrinsic<'a, 'tcx>(
736 bx: &Builder<'a, 'tcx>,
744 let (size, align) = cx.size_and_align_of(ty);
745 let size = C_usize(cx, size.bytes());
746 let align = C_i32(cx, align.abi() as i32);
747 let dst = bx.pointercast(dst, Type::i8p(cx));
748 call_memset(bx, dst, val, bx.mul(size, count), align, volatile)
751 fn try_intrinsic<'a, 'tcx>(
752 bx: &Builder<'a, 'tcx>,
759 if bx.sess().no_landing_pads() {
760 bx.call(func, &[data], None);
761 let ptr_align = bx.tcx().data_layout.pointer_align;
762 bx.store(C_null(Type::i8p(&bx.cx)), dest, ptr_align);
763 } else if wants_msvc_seh(bx.sess()) {
764 trans_msvc_try(bx, cx, func, data, local_ptr, dest);
766 trans_gnu_try(bx, cx, func, data, local_ptr, dest);
770 // MSVC's definition of the `rust_try` function.
772 // This implementation uses the new exception handling instructions in LLVM
773 // which have support in LLVM for SEH on MSVC targets. Although these
774 // instructions are meant to work for all targets, as of the time of this
775 // writing, however, LLVM does not recommend the usage of these new instructions
776 // as the old ones are still more optimized.
777 fn trans_msvc_try<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
783 let llfn = get_rust_try_fn(cx, &mut |bx| {
786 bx.set_personality_fn(bx.cx.eh_personality());
788 let normal = bx.build_sibling_block("normal");
789 let catchswitch = bx.build_sibling_block("catchswitch");
790 let catchpad = bx.build_sibling_block("catchpad");
791 let caught = bx.build_sibling_block("caught");
793 let func = llvm::get_param(bx.llfn(), 0);
794 let data = llvm::get_param(bx.llfn(), 1);
795 let local_ptr = llvm::get_param(bx.llfn(), 2);
797 // We're generating an IR snippet that looks like:
799 // declare i32 @rust_try(%func, %data, %ptr) {
800 // %slot = alloca i64*
801 // invoke %func(%data) to label %normal unwind label %catchswitch
807 // %cs = catchswitch within none [%catchpad] unwind to caller
810 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
811 // %ptr[0] = %slot[0]
812 // %ptr[1] = %slot[1]
813 // catchret from %tok to label %caught
819 // This structure follows the basic usage of throw/try/catch in LLVM.
820 // For example, compile this C++ snippet to see what LLVM generates:
822 // #include <stdint.h>
824 // int bar(void (*foo)(void), uint64_t *ret) {
828 // } catch(uint64_t a[2]) {
835 // More information can be found in libstd's seh.rs implementation.
836 let i64p = Type::i64(cx).ptr_to();
837 let ptr_align = bx.tcx().data_layout.pointer_align;
838 let slot = bx.alloca(i64p, "slot", ptr_align);
839 bx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(),
842 normal.ret(C_i32(cx, 0));
844 let cs = catchswitch.catch_switch(None, None, 1);
845 catchswitch.add_handler(cs, catchpad.llbb());
848 let tydesc = match tcx.lang_items().msvc_try_filter() {
849 Some(did) => ::consts::get_static(cx, did),
850 None => bug!("msvc_try_filter not defined"),
852 let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(cx, 0), slot]);
853 let addr = catchpad.load(slot, ptr_align);
855 let i64_align = bx.tcx().data_layout.i64_align;
856 let arg1 = catchpad.load(addr, i64_align);
857 let val1 = C_i32(cx, 1);
858 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]), i64_align);
859 let local_ptr = catchpad.bitcast(local_ptr, i64p);
860 catchpad.store(arg1, local_ptr, i64_align);
861 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), i64_align);
862 catchpad.catch_ret(tok, caught.llbb());
864 caught.ret(C_i32(cx, 1));
867 // Note that no invoke is used here because by definition this function
868 // can't panic (that's what it's catching).
869 let ret = bx.call(llfn, &[func, data, local_ptr], None);
870 let i32_align = bx.tcx().data_layout.i32_align;
871 bx.store(ret, dest, i32_align);
874 // Definition of the standard "try" function for Rust using the GNU-like model
875 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
878 // This translation is a little surprising because we always call a shim
879 // function instead of inlining the call to `invoke` manually here. This is done
880 // because in LLVM we're only allowed to have one personality per function
881 // definition. The call to the `try` intrinsic is being inlined into the
882 // function calling it, and that function may already have other personality
883 // functions in play. By calling a shim we're guaranteed that our shim will have
884 // the right personality function.
885 fn trans_gnu_try<'a, 'tcx>(bx: &Builder<'a, 'tcx>,
891 let llfn = get_rust_try_fn(cx, &mut |bx| {
894 // Translates the shims described above:
897 // invoke %func(%args...) normal %normal unwind %catch
903 // (ptr, _) = landingpad
904 // store ptr, %local_ptr
907 // Note that the `local_ptr` data passed into the `try` intrinsic is
908 // expected to be `*mut *mut u8` for this to actually work, but that's
909 // managed by the standard library.
911 let then = bx.build_sibling_block("then");
912 let catch = bx.build_sibling_block("catch");
914 let func = llvm::get_param(bx.llfn(), 0);
915 let data = llvm::get_param(bx.llfn(), 1);
916 let local_ptr = llvm::get_param(bx.llfn(), 2);
917 bx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
918 then.ret(C_i32(cx, 0));
920 // Type indicator for the exception being thrown.
922 // The first value in this tuple is a pointer to the exception object
923 // being thrown. The second value is a "selector" indicating which of
924 // the landing pad clauses the exception's type had been matched to.
925 // rust_try ignores the selector.
926 let lpad_ty = Type::struct_(cx, &[Type::i8p(cx), Type::i32(cx)],
928 let vals = catch.landing_pad(lpad_ty, bx.cx.eh_personality(), 1);
929 catch.add_clause(vals, C_null(Type::i8p(cx)));
930 let ptr = catch.extract_value(vals, 0);
931 let ptr_align = bx.tcx().data_layout.pointer_align;
932 catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(cx).ptr_to()), ptr_align);
933 catch.ret(C_i32(cx, 1));
936 // Note that no invoke is used here because by definition this function
937 // can't panic (that's what it's catching).
938 let ret = bx.call(llfn, &[func, data, local_ptr], None);
939 let i32_align = bx.tcx().data_layout.i32_align;
940 bx.store(ret, dest, i32_align);
943 // Helper function to give a Block to a closure to translate a shim function.
944 // This is currently primarily used for the `try` intrinsic functions above.
945 fn gen_fn<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
947 inputs: Vec<Ty<'tcx>>,
949 trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
951 let rust_fn_ty = cx.tcx.mk_fn_ptr(ty::Binder(cx.tcx.mk_fn_sig(
955 hir::Unsafety::Unsafe,
958 let llfn = declare::define_internal_fn(cx, name, rust_fn_ty);
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<'a, 'tcx>(cx: &CodegenCx<'a, 'tcx>,
969 trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
971 if let Some(llfn) = cx.rust_try_fn.get() {
975 // Define the type up front for the signature of the rust_try function.
977 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
978 let fn_ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
982 hir::Unsafety::Unsafe,
985 let output = tcx.types.i32;
986 let rust_try = gen_fn(cx, "__rust_try", vec![fn_ty, i8p, i8p], output, trans);
987 cx.rust_try_fn.set(Some(rust_try));
991 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
992 span_err!(a, b, E0511, "{}", c);
995 fn generic_simd_intrinsic<'a, 'tcx>(
996 bx: &Builder<'a, 'tcx>,
999 args: &[OperandRef<'tcx>],
1003 ) -> Result<ValueRef, ()> {
1004 // macros for error handling:
1005 macro_rules! emit_error {
1009 ($msg: tt, $($fmt: tt)*) => {
1010 span_invalid_monomorphization_error(
1012 &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
1017 macro_rules! require {
1018 ($cond: expr, $($fmt: tt)*) => {
1020 emit_error!($($fmt)*);
1025 macro_rules! require_simd {
1026 ($ty: expr, $position: expr) => {
1027 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
1034 let sig = tcx.erase_late_bound_regions_and_normalize(&callee_ty.fn_sig(tcx));
1035 let arg_tys = sig.inputs();
1037 // every intrinsic takes a SIMD vector as its first argument
1038 require_simd!(arg_tys[0], "input");
1039 let in_ty = arg_tys[0];
1040 let in_elem = arg_tys[0].simd_type(tcx);
1041 let in_len = arg_tys[0].simd_size(tcx);
1043 let comparison = match name {
1044 "simd_eq" => Some(hir::BiEq),
1045 "simd_ne" => Some(hir::BiNe),
1046 "simd_lt" => Some(hir::BiLt),
1047 "simd_le" => Some(hir::BiLe),
1048 "simd_gt" => Some(hir::BiGt),
1049 "simd_ge" => Some(hir::BiGe),
1053 if let Some(cmp_op) = comparison {
1054 require_simd!(ret_ty, "return");
1056 let out_len = ret_ty.simd_size(tcx);
1057 require!(in_len == out_len,
1058 "expected return type with length {} (same as input type `{}`), \
1059 found `{}` with length {}",
1062 require!(llret_ty.element_type().kind() == llvm::Integer,
1063 "expected return type with integer elements, found `{}` with non-integer `{}`",
1065 ret_ty.simd_type(tcx));
1067 return Ok(compare_simd_types(bx,
1068 args[0].immediate(),
1069 args[1].immediate(),
1075 if name.starts_with("simd_shuffle") {
1076 let n: usize = match name["simd_shuffle".len()..].parse() {
1078 Err(_) => span_bug!(span,
1079 "bad `simd_shuffle` instruction only caught in trans?")
1082 require_simd!(ret_ty, "return");
1084 let out_len = ret_ty.simd_size(tcx);
1085 require!(out_len == n,
1086 "expected return type of length {}, found `{}` with length {}",
1087 n, ret_ty, out_len);
1088 require!(in_elem == ret_ty.simd_type(tcx),
1089 "expected return element type `{}` (element of input `{}`), \
1090 found `{}` with element type `{}`",
1092 ret_ty, ret_ty.simd_type(tcx));
1094 let total_len = in_len as u128 * 2;
1096 let vector = args[2].immediate();
1098 let indices: Option<Vec<_>> = (0..n)
1101 let val = const_get_elt(vector, i as u64);
1102 match const_to_opt_u128(val, true) {
1104 emit_error!("shuffle index #{} is not a constant", arg_idx);
1107 Some(idx) if idx >= total_len => {
1108 emit_error!("shuffle index #{} is out of bounds (limit {})",
1109 arg_idx, total_len);
1112 Some(idx) => Some(C_i32(bx.cx, idx as i32)),
1116 let indices = match indices {
1118 None => return Ok(C_null(llret_ty))
1121 return Ok(bx.shuffle_vector(args[0].immediate(),
1122 args[1].immediate(),
1123 C_vector(&indices)))
1126 if name == "simd_insert" {
1127 require!(in_elem == arg_tys[2],
1128 "expected inserted type `{}` (element of input `{}`), found `{}`",
1129 in_elem, in_ty, arg_tys[2]);
1130 return Ok(bx.insert_element(args[0].immediate(),
1131 args[2].immediate(),
1132 args[1].immediate()))
1134 if name == "simd_extract" {
1135 require!(ret_ty == in_elem,
1136 "expected return type `{}` (element of input `{}`), found `{}`",
1137 in_elem, in_ty, ret_ty);
1138 return Ok(bx.extract_element(args[0].immediate(), args[1].immediate()))
1141 if name == "simd_cast" {
1142 require_simd!(ret_ty, "return");
1143 let out_len = ret_ty.simd_size(tcx);
1144 require!(in_len == out_len,
1145 "expected return type with length {} (same as input type `{}`), \
1146 found `{}` with length {}",
1149 // casting cares about nominal type, not just structural type
1150 let out_elem = ret_ty.simd_type(tcx);
1152 if in_elem == out_elem { return Ok(args[0].immediate()); }
1154 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1156 let (in_style, in_width) = match in_elem.sty {
1157 // vectors of pointer-sized integers should've been
1158 // disallowed before here, so this unwrap is safe.
1159 ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1160 ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1161 ty::TyFloat(f) => (Style::Float, f.bit_width()),
1162 _ => (Style::Unsupported, 0)
1164 let (out_style, out_width) = match out_elem.sty {
1165 ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1166 ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1167 ty::TyFloat(f) => (Style::Float, f.bit_width()),
1168 _ => (Style::Unsupported, 0)
1171 match (in_style, out_style) {
1172 (Style::Int(in_is_signed), Style::Int(_)) => {
1173 return Ok(match in_width.cmp(&out_width) {
1174 Ordering::Greater => bx.trunc(args[0].immediate(), llret_ty),
1175 Ordering::Equal => args[0].immediate(),
1176 Ordering::Less => if in_is_signed {
1177 bx.sext(args[0].immediate(), llret_ty)
1179 bx.zext(args[0].immediate(), llret_ty)
1183 (Style::Int(in_is_signed), Style::Float) => {
1184 return Ok(if in_is_signed {
1185 bx.sitofp(args[0].immediate(), llret_ty)
1187 bx.uitofp(args[0].immediate(), llret_ty)
1190 (Style::Float, Style::Int(out_is_signed)) => {
1191 return Ok(if out_is_signed {
1192 bx.fptosi(args[0].immediate(), llret_ty)
1194 bx.fptoui(args[0].immediate(), llret_ty)
1197 (Style::Float, Style::Float) => {
1198 return Ok(match in_width.cmp(&out_width) {
1199 Ordering::Greater => bx.fptrunc(args[0].immediate(), llret_ty),
1200 Ordering::Equal => args[0].immediate(),
1201 Ordering::Less => bx.fpext(args[0].immediate(), llret_ty)
1204 _ => {/* Unsupported. Fallthrough. */}
1207 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1211 macro_rules! arith {
1212 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1213 $(if name == stringify!($name) {
1215 $($(ty::$p(_))|* => {
1216 return Ok(bx.$call(args[0].immediate(), args[1].immediate()))
1221 "unsupported operation on `{}` with element `{}`",
1228 simd_add: TyUint, TyInt => add, TyFloat => fadd;
1229 simd_sub: TyUint, TyInt => sub, TyFloat => fsub;
1230 simd_mul: TyUint, TyInt => mul, TyFloat => fmul;
1231 simd_div: TyUint => udiv, TyInt => sdiv, TyFloat => fdiv;
1232 simd_rem: TyUint => urem, TyInt => srem, TyFloat => frem;
1233 simd_shl: TyUint, TyInt => shl;
1234 simd_shr: TyUint => lshr, TyInt => ashr;
1235 simd_and: TyUint, TyInt => and;
1236 simd_or: TyUint, TyInt => or;
1237 simd_xor: TyUint, TyInt => xor;
1239 span_bug!(span, "unknown SIMD intrinsic");
1242 // Returns the width of an int Ty, and if it's signed or not
1243 // Returns None if the type is not an integer
1244 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1246 fn int_type_width_signed(ty: Ty, cx: &CodegenCx) -> Option<(u64, bool)> {
1248 ty::TyInt(t) => Some((match t {
1249 ast::IntTy::Isize => {
1250 match &cx.tcx.sess.target.target.target_pointer_width[..] {
1254 tws => bug!("Unsupported target word size for isize: {}", tws),
1257 ast::IntTy::I8 => 8,
1258 ast::IntTy::I16 => 16,
1259 ast::IntTy::I32 => 32,
1260 ast::IntTy::I64 => 64,
1261 ast::IntTy::I128 => 128,
1263 ty::TyUint(t) => Some((match t {
1264 ast::UintTy::Usize => {
1265 match &cx.tcx.sess.target.target.target_pointer_width[..] {
1269 tws => bug!("Unsupported target word size for usize: {}", tws),
1272 ast::UintTy::U8 => 8,
1273 ast::UintTy::U16 => 16,
1274 ast::UintTy::U32 => 32,
1275 ast::UintTy::U64 => 64,
1276 ast::UintTy::U128 => 128,
1282 // Returns the width of a float TypeVariant
1283 // Returns None if the type is not a float
1284 fn float_type_width<'tcx>(sty: &ty::TypeVariants<'tcx>)
1286 use rustc::ty::TyFloat;
1288 TyFloat(t) => Some(match t {
1289 ast::FloatTy::F32 => 32,
1290 ast::FloatTy::F64 => 64,